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/CodeGen/CGFunctionInfo.h" 24 #include "clang/CodeGen/SwiftCallingConv.h" 25 #include "llvm/ADT/SmallBitVector.h" 26 #include "llvm/ADT/StringExtras.h" 27 #include "llvm/ADT/StringSwitch.h" 28 #include "llvm/ADT/Triple.h" 29 #include "llvm/ADT/Twine.h" 30 #include "llvm/IR/DataLayout.h" 31 #include "llvm/IR/Type.h" 32 #include "llvm/Support/raw_ostream.h" 33 #include <algorithm> // std::sort 34 35 using namespace clang; 36 using namespace CodeGen; 37 38 // Helper for coercing an aggregate argument or return value into an integer 39 // array of the same size (including padding) and alignment. This alternate 40 // coercion happens only for the RenderScript ABI and can be removed after 41 // runtimes that rely on it are no longer supported. 42 // 43 // RenderScript assumes that the size of the argument / return value in the IR 44 // is the same as the size of the corresponding qualified type. This helper 45 // coerces the aggregate type into an array of the same size (including 46 // padding). This coercion is used in lieu of expansion of struct members or 47 // other canonical coercions that return a coerced-type of larger size. 48 // 49 // Ty - The argument / return value type 50 // Context - The associated ASTContext 51 // LLVMContext - The associated LLVMContext 52 static ABIArgInfo coerceToIntArray(QualType Ty, 53 ASTContext &Context, 54 llvm::LLVMContext &LLVMContext) { 55 // Alignment and Size are measured in bits. 56 const uint64_t Size = Context.getTypeSize(Ty); 57 const uint64_t Alignment = Context.getTypeAlign(Ty); 58 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment); 59 const uint64_t NumElements = (Size + Alignment - 1) / Alignment; 60 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 61 } 62 63 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder, 64 llvm::Value *Array, 65 llvm::Value *Value, 66 unsigned FirstIndex, 67 unsigned LastIndex) { 68 // Alternatively, we could emit this as a loop in the source. 69 for (unsigned I = FirstIndex; I <= LastIndex; ++I) { 70 llvm::Value *Cell = 71 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I); 72 Builder.CreateAlignedStore(Value, Cell, CharUnits::One()); 73 } 74 } 75 76 static bool isAggregateTypeForABI(QualType T) { 77 return !CodeGenFunction::hasScalarEvaluationKind(T) || 78 T->isMemberFunctionPointerType(); 79 } 80 81 ABIArgInfo 82 ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign, 83 llvm::Type *Padding) const { 84 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), 85 ByRef, Realign, Padding); 86 } 87 88 ABIArgInfo 89 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const { 90 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty), 91 /*ByRef*/ false, Realign); 92 } 93 94 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 95 QualType Ty) const { 96 return Address::invalid(); 97 } 98 99 ABIInfo::~ABIInfo() {} 100 101 /// Does the given lowering require more than the given number of 102 /// registers when expanded? 103 /// 104 /// This is intended to be the basis of a reasonable basic implementation 105 /// of should{Pass,Return}IndirectlyForSwift. 106 /// 107 /// For most targets, a limit of four total registers is reasonable; this 108 /// limits the amount of code required in order to move around the value 109 /// in case it wasn't produced immediately prior to the call by the caller 110 /// (or wasn't produced in exactly the right registers) or isn't used 111 /// immediately within the callee. But some targets may need to further 112 /// limit the register count due to an inability to support that many 113 /// return registers. 114 static bool occupiesMoreThan(CodeGenTypes &cgt, 115 ArrayRef<llvm::Type*> scalarTypes, 116 unsigned maxAllRegisters) { 117 unsigned intCount = 0, fpCount = 0; 118 for (llvm::Type *type : scalarTypes) { 119 if (type->isPointerTy()) { 120 intCount++; 121 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) { 122 auto ptrWidth = cgt.getTarget().getPointerWidth(0); 123 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth; 124 } else { 125 assert(type->isVectorTy() || type->isFloatingPointTy()); 126 fpCount++; 127 } 128 } 129 130 return (intCount + fpCount > maxAllRegisters); 131 } 132 133 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 134 llvm::Type *eltTy, 135 unsigned numElts) const { 136 // The default implementation of this assumes that the target guarantees 137 // 128-bit SIMD support but nothing more. 138 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16); 139 } 140 141 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, 142 CGCXXABI &CXXABI) { 143 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 144 if (!RD) { 145 if (!RT->getDecl()->canPassInRegisters()) 146 return CGCXXABI::RAA_Indirect; 147 return CGCXXABI::RAA_Default; 148 } 149 return CXXABI.getRecordArgABI(RD); 150 } 151 152 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T, 153 CGCXXABI &CXXABI) { 154 const RecordType *RT = T->getAs<RecordType>(); 155 if (!RT) 156 return CGCXXABI::RAA_Default; 157 return getRecordArgABI(RT, CXXABI); 158 } 159 160 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, 161 const ABIInfo &Info) { 162 QualType Ty = FI.getReturnType(); 163 164 if (const auto *RT = Ty->getAs<RecordType>()) 165 if (!isa<CXXRecordDecl>(RT->getDecl()) && 166 !RT->getDecl()->canPassInRegisters()) { 167 FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty); 168 return true; 169 } 170 171 return CXXABI.classifyReturnType(FI); 172 } 173 174 /// Pass transparent unions as if they were the type of the first element. Sema 175 /// should ensure that all elements of the union have the same "machine type". 176 static QualType useFirstFieldIfTransparentUnion(QualType Ty) { 177 if (const RecordType *UT = Ty->getAsUnionType()) { 178 const RecordDecl *UD = UT->getDecl(); 179 if (UD->hasAttr<TransparentUnionAttr>()) { 180 assert(!UD->field_empty() && "sema created an empty transparent union"); 181 return UD->field_begin()->getType(); 182 } 183 } 184 return Ty; 185 } 186 187 CGCXXABI &ABIInfo::getCXXABI() const { 188 return CGT.getCXXABI(); 189 } 190 191 ASTContext &ABIInfo::getContext() const { 192 return CGT.getContext(); 193 } 194 195 llvm::LLVMContext &ABIInfo::getVMContext() const { 196 return CGT.getLLVMContext(); 197 } 198 199 const llvm::DataLayout &ABIInfo::getDataLayout() const { 200 return CGT.getDataLayout(); 201 } 202 203 const TargetInfo &ABIInfo::getTarget() const { 204 return CGT.getTarget(); 205 } 206 207 const CodeGenOptions &ABIInfo::getCodeGenOpts() const { 208 return CGT.getCodeGenOpts(); 209 } 210 211 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); } 212 213 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 214 return false; 215 } 216 217 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 218 uint64_t Members) const { 219 return false; 220 } 221 222 LLVM_DUMP_METHOD void ABIArgInfo::dump() const { 223 raw_ostream &OS = llvm::errs(); 224 OS << "(ABIArgInfo Kind="; 225 switch (TheKind) { 226 case Direct: 227 OS << "Direct Type="; 228 if (llvm::Type *Ty = getCoerceToType()) 229 Ty->print(OS); 230 else 231 OS << "null"; 232 break; 233 case Extend: 234 OS << "Extend"; 235 break; 236 case Ignore: 237 OS << "Ignore"; 238 break; 239 case InAlloca: 240 OS << "InAlloca Offset=" << getInAllocaFieldIndex(); 241 break; 242 case Indirect: 243 OS << "Indirect Align=" << getIndirectAlign().getQuantity() 244 << " ByVal=" << getIndirectByVal() 245 << " Realign=" << getIndirectRealign(); 246 break; 247 case Expand: 248 OS << "Expand"; 249 break; 250 case CoerceAndExpand: 251 OS << "CoerceAndExpand Type="; 252 getCoerceAndExpandType()->print(OS); 253 break; 254 } 255 OS << ")\n"; 256 } 257 258 // Dynamically round a pointer up to a multiple of the given alignment. 259 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF, 260 llvm::Value *Ptr, 261 CharUnits Align) { 262 llvm::Value *PtrAsInt = Ptr; 263 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align; 264 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy); 265 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt, 266 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1)); 267 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt, 268 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity())); 269 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt, 270 Ptr->getType(), 271 Ptr->getName() + ".aligned"); 272 return PtrAsInt; 273 } 274 275 /// Emit va_arg for a platform using the common void* representation, 276 /// where arguments are simply emitted in an array of slots on the stack. 277 /// 278 /// This version implements the core direct-value passing rules. 279 /// 280 /// \param SlotSize - The size and alignment of a stack slot. 281 /// Each argument will be allocated to a multiple of this number of 282 /// slots, and all the slots will be aligned to this value. 283 /// \param AllowHigherAlign - The slot alignment is not a cap; 284 /// an argument type with an alignment greater than the slot size 285 /// will be emitted on a higher-alignment address, potentially 286 /// leaving one or more empty slots behind as padding. If this 287 /// is false, the returned address might be less-aligned than 288 /// DirectAlign. 289 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF, 290 Address VAListAddr, 291 llvm::Type *DirectTy, 292 CharUnits DirectSize, 293 CharUnits DirectAlign, 294 CharUnits SlotSize, 295 bool AllowHigherAlign) { 296 // Cast the element type to i8* if necessary. Some platforms define 297 // va_list as a struct containing an i8* instead of just an i8*. 298 if (VAListAddr.getElementType() != CGF.Int8PtrTy) 299 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy); 300 301 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur"); 302 303 // If the CC aligns values higher than the slot size, do so if needed. 304 Address Addr = Address::invalid(); 305 if (AllowHigherAlign && DirectAlign > SlotSize) { 306 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign), 307 DirectAlign); 308 } else { 309 Addr = Address(Ptr, SlotSize); 310 } 311 312 // Advance the pointer past the argument, then store that back. 313 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize); 314 Address NextPtr = 315 CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next"); 316 CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 317 318 // If the argument is smaller than a slot, and this is a big-endian 319 // target, the argument will be right-adjusted in its slot. 320 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() && 321 !DirectTy->isStructTy()) { 322 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize); 323 } 324 325 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy); 326 return Addr; 327 } 328 329 /// Emit va_arg for a platform using the common void* representation, 330 /// where arguments are simply emitted in an array of slots on the stack. 331 /// 332 /// \param IsIndirect - Values of this type are passed indirectly. 333 /// \param ValueInfo - The size and alignment of this type, generally 334 /// computed with getContext().getTypeInfoInChars(ValueTy). 335 /// \param SlotSizeAndAlign - The size and alignment of a stack slot. 336 /// Each argument will be allocated to a multiple of this number of 337 /// slots, and all the slots will be aligned to this value. 338 /// \param AllowHigherAlign - The slot alignment is not a cap; 339 /// an argument type with an alignment greater than the slot size 340 /// will be emitted on a higher-alignment address, potentially 341 /// leaving one or more empty slots behind as padding. 342 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr, 343 QualType ValueTy, bool IsIndirect, 344 std::pair<CharUnits, CharUnits> ValueInfo, 345 CharUnits SlotSizeAndAlign, 346 bool AllowHigherAlign) { 347 // The size and alignment of the value that was passed directly. 348 CharUnits DirectSize, DirectAlign; 349 if (IsIndirect) { 350 DirectSize = CGF.getPointerSize(); 351 DirectAlign = CGF.getPointerAlign(); 352 } else { 353 DirectSize = ValueInfo.first; 354 DirectAlign = ValueInfo.second; 355 } 356 357 // Cast the address we've calculated to the right type. 358 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy); 359 if (IsIndirect) 360 DirectTy = DirectTy->getPointerTo(0); 361 362 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy, 363 DirectSize, DirectAlign, 364 SlotSizeAndAlign, 365 AllowHigherAlign); 366 367 if (IsIndirect) { 368 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second); 369 } 370 371 return Addr; 372 373 } 374 375 static Address emitMergePHI(CodeGenFunction &CGF, 376 Address Addr1, llvm::BasicBlock *Block1, 377 Address Addr2, llvm::BasicBlock *Block2, 378 const llvm::Twine &Name = "") { 379 assert(Addr1.getType() == Addr2.getType()); 380 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name); 381 PHI->addIncoming(Addr1.getPointer(), Block1); 382 PHI->addIncoming(Addr2.getPointer(), Block2); 383 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment()); 384 return Address(PHI, Align); 385 } 386 387 TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; } 388 389 // If someone can figure out a general rule for this, that would be great. 390 // It's probably just doomed to be platform-dependent, though. 391 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const { 392 // Verified for: 393 // x86-64 FreeBSD, Linux, Darwin 394 // x86-32 FreeBSD, Linux, Darwin 395 // PowerPC Linux, Darwin 396 // ARM Darwin (*not* EABI) 397 // AArch64 Linux 398 return 32; 399 } 400 401 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args, 402 const FunctionNoProtoType *fnType) const { 403 // The following conventions are known to require this to be false: 404 // x86_stdcall 405 // MIPS 406 // For everything else, we just prefer false unless we opt out. 407 return false; 408 } 409 410 void 411 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib, 412 llvm::SmallString<24> &Opt) const { 413 // This assumes the user is passing a library name like "rt" instead of a 414 // filename like "librt.a/so", and that they don't care whether it's static or 415 // dynamic. 416 Opt = "-l"; 417 Opt += Lib; 418 } 419 420 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const { 421 // OpenCL kernels are called via an explicit runtime API with arguments 422 // set with clSetKernelArg(), not as normal sub-functions. 423 // Return SPIR_KERNEL by default as the kernel calling convention to 424 // ensure the fingerprint is fixed such way that each OpenCL argument 425 // gets one matching argument in the produced kernel function argument 426 // list to enable feasible implementation of clSetKernelArg() with 427 // aggregates etc. In case we would use the default C calling conv here, 428 // clSetKernelArg() might break depending on the target-specific 429 // conventions; different targets might split structs passed as values 430 // to multiple function arguments etc. 431 return llvm::CallingConv::SPIR_KERNEL; 432 } 433 434 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM, 435 llvm::PointerType *T, QualType QT) const { 436 return llvm::ConstantPointerNull::get(T); 437 } 438 439 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 440 const VarDecl *D) const { 441 assert(!CGM.getLangOpts().OpenCL && 442 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 443 "Address space agnostic languages only"); 444 return D ? D->getType().getAddressSpace() : LangAS::Default; 445 } 446 447 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast( 448 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr, 449 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const { 450 // Since target may map different address spaces in AST to the same address 451 // space, an address space conversion may end up as a bitcast. 452 if (auto *C = dyn_cast<llvm::Constant>(Src)) 453 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy); 454 // Try to preserve the source's name to make IR more readable. 455 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 456 Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : ""); 457 } 458 459 llvm::Constant * 460 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src, 461 LangAS SrcAddr, LangAS DestAddr, 462 llvm::Type *DestTy) const { 463 // Since target may map different address spaces in AST to the same address 464 // space, an address space conversion may end up as a bitcast. 465 return llvm::ConstantExpr::getPointerCast(Src, DestTy); 466 } 467 468 llvm::SyncScope::ID 469 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 470 SyncScope Scope, 471 llvm::AtomicOrdering Ordering, 472 llvm::LLVMContext &Ctx) const { 473 return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */ 474 } 475 476 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays); 477 478 /// isEmptyField - Return true iff a the field is "empty", that is it 479 /// is an unnamed bit-field or an (array of) empty record(s). 480 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD, 481 bool AllowArrays) { 482 if (FD->isUnnamedBitfield()) 483 return true; 484 485 QualType FT = FD->getType(); 486 487 // Constant arrays of empty records count as empty, strip them off. 488 // Constant arrays of zero length always count as empty. 489 if (AllowArrays) 490 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 491 if (AT->getSize() == 0) 492 return true; 493 FT = AT->getElementType(); 494 } 495 496 const RecordType *RT = FT->getAs<RecordType>(); 497 if (!RT) 498 return false; 499 500 // C++ record fields are never empty, at least in the Itanium ABI. 501 // 502 // FIXME: We should use a predicate for whether this behavior is true in the 503 // current ABI. 504 if (isa<CXXRecordDecl>(RT->getDecl())) 505 return false; 506 507 return isEmptyRecord(Context, FT, AllowArrays); 508 } 509 510 /// isEmptyRecord - Return true iff a structure contains only empty 511 /// fields. Note that a structure with a flexible array member is not 512 /// considered empty. 513 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) { 514 const RecordType *RT = T->getAs<RecordType>(); 515 if (!RT) 516 return false; 517 const RecordDecl *RD = RT->getDecl(); 518 if (RD->hasFlexibleArrayMember()) 519 return false; 520 521 // If this is a C++ record, check the bases first. 522 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 523 for (const auto &I : CXXRD->bases()) 524 if (!isEmptyRecord(Context, I.getType(), true)) 525 return false; 526 527 for (const auto *I : RD->fields()) 528 if (!isEmptyField(Context, I, AllowArrays)) 529 return false; 530 return true; 531 } 532 533 /// isSingleElementStruct - Determine if a structure is a "single 534 /// element struct", i.e. it has exactly one non-empty field or 535 /// exactly one field which is itself a single element 536 /// struct. Structures with flexible array members are never 537 /// considered single element structs. 538 /// 539 /// \return The field declaration for the single non-empty field, if 540 /// it exists. 541 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) { 542 const RecordType *RT = T->getAs<RecordType>(); 543 if (!RT) 544 return nullptr; 545 546 const RecordDecl *RD = RT->getDecl(); 547 if (RD->hasFlexibleArrayMember()) 548 return nullptr; 549 550 const Type *Found = nullptr; 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 // Ignore empty records. 556 if (isEmptyRecord(Context, I.getType(), true)) 557 continue; 558 559 // If we already found an element then this isn't a single-element struct. 560 if (Found) 561 return nullptr; 562 563 // If this is non-empty and not a single element struct, the composite 564 // cannot be a single element struct. 565 Found = isSingleElementStruct(I.getType(), Context); 566 if (!Found) 567 return nullptr; 568 } 569 } 570 571 // Check for single element. 572 for (const auto *FD : RD->fields()) { 573 QualType FT = FD->getType(); 574 575 // Ignore empty fields. 576 if (isEmptyField(Context, FD, true)) 577 continue; 578 579 // If we already found an element then this isn't a single-element 580 // struct. 581 if (Found) 582 return nullptr; 583 584 // Treat single element arrays as the element. 585 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 586 if (AT->getSize().getZExtValue() != 1) 587 break; 588 FT = AT->getElementType(); 589 } 590 591 if (!isAggregateTypeForABI(FT)) { 592 Found = FT.getTypePtr(); 593 } else { 594 Found = isSingleElementStruct(FT, Context); 595 if (!Found) 596 return nullptr; 597 } 598 } 599 600 // We don't consider a struct a single-element struct if it has 601 // padding beyond the element type. 602 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T)) 603 return nullptr; 604 605 return Found; 606 } 607 608 namespace { 609 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty, 610 const ABIArgInfo &AI) { 611 // This default implementation defers to the llvm backend's va_arg 612 // instruction. It can handle only passing arguments directly 613 // (typically only handled in the backend for primitive types), or 614 // aggregates passed indirectly by pointer (NOTE: if the "byval" 615 // flag has ABI impact in the callee, this implementation cannot 616 // work.) 617 618 // Only a few cases are covered here at the moment -- those needed 619 // by the default abi. 620 llvm::Value *Val; 621 622 if (AI.isIndirect()) { 623 assert(!AI.getPaddingType() && 624 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 625 assert( 626 !AI.getIndirectRealign() && 627 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!"); 628 629 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty); 630 CharUnits TyAlignForABI = TyInfo.second; 631 632 llvm::Type *BaseTy = 633 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 634 llvm::Value *Addr = 635 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy); 636 return Address(Addr, TyAlignForABI); 637 } else { 638 assert((AI.isDirect() || AI.isExtend()) && 639 "Unexpected ArgInfo Kind in generic VAArg emitter!"); 640 641 assert(!AI.getInReg() && 642 "Unexpected InReg seen in arginfo in generic VAArg emitter!"); 643 assert(!AI.getPaddingType() && 644 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 645 assert(!AI.getDirectOffset() && 646 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!"); 647 assert(!AI.getCoerceToType() && 648 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!"); 649 650 Address Temp = CGF.CreateMemTemp(Ty, "varet"); 651 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty)); 652 CGF.Builder.CreateStore(Val, Temp); 653 return Temp; 654 } 655 } 656 657 /// DefaultABIInfo - The default implementation for ABI specific 658 /// details. This implementation provides information which results in 659 /// self-consistent and sensible LLVM IR generation, but does not 660 /// conform to any particular ABI. 661 class DefaultABIInfo : public ABIInfo { 662 public: 663 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 664 665 ABIArgInfo classifyReturnType(QualType RetTy) const; 666 ABIArgInfo classifyArgumentType(QualType RetTy) const; 667 668 void computeInfo(CGFunctionInfo &FI) const override { 669 if (!getCXXABI().classifyReturnType(FI)) 670 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 671 for (auto &I : FI.arguments()) 672 I.info = classifyArgumentType(I.type); 673 } 674 675 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 676 QualType Ty) const override { 677 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 678 } 679 }; 680 681 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo { 682 public: 683 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 684 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 685 }; 686 687 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const { 688 Ty = useFirstFieldIfTransparentUnion(Ty); 689 690 if (isAggregateTypeForABI(Ty)) { 691 // Records with non-trivial destructors/copy-constructors should not be 692 // passed by value. 693 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 694 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 695 696 return getNaturalAlignIndirect(Ty); 697 } 698 699 // Treat an enum type as its underlying type. 700 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 701 Ty = EnumTy->getDecl()->getIntegerType(); 702 703 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 704 : ABIArgInfo::getDirect()); 705 } 706 707 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const { 708 if (RetTy->isVoidType()) 709 return ABIArgInfo::getIgnore(); 710 711 if (isAggregateTypeForABI(RetTy)) 712 return getNaturalAlignIndirect(RetTy); 713 714 // Treat an enum type as its underlying type. 715 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 716 RetTy = EnumTy->getDecl()->getIntegerType(); 717 718 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 719 : ABIArgInfo::getDirect()); 720 } 721 722 //===----------------------------------------------------------------------===// 723 // WebAssembly ABI Implementation 724 // 725 // This is a very simple ABI that relies a lot on DefaultABIInfo. 726 //===----------------------------------------------------------------------===// 727 728 class WebAssemblyABIInfo final : public SwiftABIInfo { 729 DefaultABIInfo defaultInfo; 730 731 public: 732 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT) 733 : SwiftABIInfo(CGT), defaultInfo(CGT) {} 734 735 private: 736 ABIArgInfo classifyReturnType(QualType RetTy) const; 737 ABIArgInfo classifyArgumentType(QualType Ty) const; 738 739 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 740 // non-virtual, but computeInfo and EmitVAArg are virtual, so we 741 // overload them. 742 void computeInfo(CGFunctionInfo &FI) const override { 743 if (!getCXXABI().classifyReturnType(FI)) 744 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 745 for (auto &Arg : FI.arguments()) 746 Arg.info = classifyArgumentType(Arg.type); 747 } 748 749 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 750 QualType Ty) const override; 751 752 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 753 bool asReturnValue) const override { 754 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 755 } 756 757 bool isSwiftErrorInRegister() const override { 758 return false; 759 } 760 }; 761 762 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo { 763 public: 764 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 765 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {} 766 767 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 768 CodeGen::CodeGenModule &CGM) const override { 769 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 770 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 771 if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) { 772 llvm::Function *Fn = cast<llvm::Function>(GV); 773 llvm::AttrBuilder B; 774 B.addAttribute("wasm-import-module", Attr->getImportModule()); 775 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 776 } 777 if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) { 778 llvm::Function *Fn = cast<llvm::Function>(GV); 779 llvm::AttrBuilder B; 780 B.addAttribute("wasm-import-name", Attr->getImportName()); 781 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 782 } 783 if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) { 784 llvm::Function *Fn = cast<llvm::Function>(GV); 785 llvm::AttrBuilder B; 786 B.addAttribute("wasm-export-name", Attr->getExportName()); 787 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 788 } 789 } 790 791 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 792 llvm::Function *Fn = cast<llvm::Function>(GV); 793 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype()) 794 Fn->addFnAttr("no-prototype"); 795 } 796 } 797 }; 798 799 /// Classify argument of given type \p Ty. 800 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const { 801 Ty = useFirstFieldIfTransparentUnion(Ty); 802 803 if (isAggregateTypeForABI(Ty)) { 804 // Records with non-trivial destructors/copy-constructors should not be 805 // passed by value. 806 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 807 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 808 // Ignore empty structs/unions. 809 if (isEmptyRecord(getContext(), Ty, true)) 810 return ABIArgInfo::getIgnore(); 811 // Lower single-element structs to just pass a regular value. TODO: We 812 // could do reasonable-size multiple-element structs too, using getExpand(), 813 // though watch out for things like bitfields. 814 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 815 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 816 } 817 818 // Otherwise just do the default thing. 819 return defaultInfo.classifyArgumentType(Ty); 820 } 821 822 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const { 823 if (isAggregateTypeForABI(RetTy)) { 824 // Records with non-trivial destructors/copy-constructors should not be 825 // returned by value. 826 if (!getRecordArgABI(RetTy, getCXXABI())) { 827 // Ignore empty structs/unions. 828 if (isEmptyRecord(getContext(), RetTy, true)) 829 return ABIArgInfo::getIgnore(); 830 // Lower single-element structs to just return a regular value. TODO: We 831 // could do reasonable-size multiple-element structs too, using 832 // ABIArgInfo::getDirect(). 833 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 834 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 835 } 836 } 837 838 // Otherwise just do the default thing. 839 return defaultInfo.classifyReturnType(RetTy); 840 } 841 842 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 843 QualType Ty) const { 844 bool IsIndirect = isAggregateTypeForABI(Ty) && 845 !isEmptyRecord(getContext(), Ty, true) && 846 !isSingleElementStruct(Ty, getContext()); 847 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 848 getContext().getTypeInfoInChars(Ty), 849 CharUnits::fromQuantity(4), 850 /*AllowHigherAlign=*/true); 851 } 852 853 //===----------------------------------------------------------------------===// 854 // le32/PNaCl bitcode ABI Implementation 855 // 856 // This is a simplified version of the x86_32 ABI. Arguments and return values 857 // are always passed on the stack. 858 //===----------------------------------------------------------------------===// 859 860 class PNaClABIInfo : public ABIInfo { 861 public: 862 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 863 864 ABIArgInfo classifyReturnType(QualType RetTy) const; 865 ABIArgInfo classifyArgumentType(QualType RetTy) const; 866 867 void computeInfo(CGFunctionInfo &FI) const override; 868 Address EmitVAArg(CodeGenFunction &CGF, 869 Address VAListAddr, QualType Ty) const override; 870 }; 871 872 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo { 873 public: 874 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 875 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {} 876 }; 877 878 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const { 879 if (!getCXXABI().classifyReturnType(FI)) 880 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 881 882 for (auto &I : FI.arguments()) 883 I.info = classifyArgumentType(I.type); 884 } 885 886 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 887 QualType Ty) const { 888 // The PNaCL ABI is a bit odd, in that varargs don't use normal 889 // function classification. Structs get passed directly for varargs 890 // functions, through a rewriting transform in 891 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows 892 // this target to actually support a va_arg instructions with an 893 // aggregate type, unlike other targets. 894 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 895 } 896 897 /// Classify argument of given type \p Ty. 898 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const { 899 if (isAggregateTypeForABI(Ty)) { 900 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 901 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 902 return getNaturalAlignIndirect(Ty); 903 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 904 // Treat an enum type as its underlying type. 905 Ty = EnumTy->getDecl()->getIntegerType(); 906 } else if (Ty->isFloatingType()) { 907 // Floating-point types don't go inreg. 908 return ABIArgInfo::getDirect(); 909 } 910 911 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 912 : ABIArgInfo::getDirect()); 913 } 914 915 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const { 916 if (RetTy->isVoidType()) 917 return ABIArgInfo::getIgnore(); 918 919 // In the PNaCl ABI we always return records/structures on the stack. 920 if (isAggregateTypeForABI(RetTy)) 921 return getNaturalAlignIndirect(RetTy); 922 923 // Treat an enum type as its underlying type. 924 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 925 RetTy = EnumTy->getDecl()->getIntegerType(); 926 927 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 928 : ABIArgInfo::getDirect()); 929 } 930 931 /// IsX86_MMXType - Return true if this is an MMX type. 932 bool IsX86_MMXType(llvm::Type *IRType) { 933 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>. 934 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 && 935 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() && 936 IRType->getScalarSizeInBits() != 64; 937 } 938 939 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 940 StringRef Constraint, 941 llvm::Type* Ty) { 942 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint) 943 .Cases("y", "&y", "^Ym", true) 944 .Default(false); 945 if (IsMMXCons && Ty->isVectorTy()) { 946 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) { 947 // Invalid MMX constraint 948 return nullptr; 949 } 950 951 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); 952 } 953 954 // No operation needed 955 return Ty; 956 } 957 958 /// Returns true if this type can be passed in SSE registers with the 959 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64. 960 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) { 961 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 962 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) { 963 if (BT->getKind() == BuiltinType::LongDouble) { 964 if (&Context.getTargetInfo().getLongDoubleFormat() == 965 &llvm::APFloat::x87DoubleExtended()) 966 return false; 967 } 968 return true; 969 } 970 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 971 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX 972 // registers specially. 973 unsigned VecSize = Context.getTypeSize(VT); 974 if (VecSize == 128 || VecSize == 256 || VecSize == 512) 975 return true; 976 } 977 return false; 978 } 979 980 /// Returns true if this aggregate is small enough to be passed in SSE registers 981 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64. 982 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) { 983 return NumMembers <= 4; 984 } 985 986 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86. 987 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) { 988 auto AI = ABIArgInfo::getDirect(T); 989 AI.setInReg(true); 990 AI.setCanBeFlattened(false); 991 return AI; 992 } 993 994 //===----------------------------------------------------------------------===// 995 // X86-32 ABI Implementation 996 //===----------------------------------------------------------------------===// 997 998 /// Similar to llvm::CCState, but for Clang. 999 struct CCState { 1000 CCState(CGFunctionInfo &FI) 1001 : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {} 1002 1003 llvm::SmallBitVector IsPreassigned; 1004 unsigned CC = CallingConv::CC_C; 1005 unsigned FreeRegs = 0; 1006 unsigned FreeSSERegs = 0; 1007 }; 1008 1009 enum { 1010 // Vectorcall only allows the first 6 parameters to be passed in registers. 1011 VectorcallMaxParamNumAsReg = 6 1012 }; 1013 1014 /// X86_32ABIInfo - The X86-32 ABI information. 1015 class X86_32ABIInfo : public SwiftABIInfo { 1016 enum Class { 1017 Integer, 1018 Float 1019 }; 1020 1021 static const unsigned MinABIStackAlignInBytes = 4; 1022 1023 bool IsDarwinVectorABI; 1024 bool IsRetSmallStructInRegABI; 1025 bool IsWin32StructABI; 1026 bool IsSoftFloatABI; 1027 bool IsMCUABI; 1028 unsigned DefaultNumRegisterParameters; 1029 1030 static bool isRegisterSize(unsigned Size) { 1031 return (Size == 8 || Size == 16 || Size == 32 || Size == 64); 1032 } 1033 1034 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 1035 // FIXME: Assumes vectorcall is in use. 1036 return isX86VectorTypeForVectorCall(getContext(), Ty); 1037 } 1038 1039 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 1040 uint64_t NumMembers) const override { 1041 // FIXME: Assumes vectorcall is in use. 1042 return isX86VectorCallAggregateSmallEnough(NumMembers); 1043 } 1044 1045 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const; 1046 1047 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1048 /// such that the argument will be passed in memory. 1049 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 1050 1051 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const; 1052 1053 /// Return the alignment to use for the given type on the stack. 1054 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; 1055 1056 Class classify(QualType Ty) const; 1057 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; 1058 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 1059 1060 /// Updates the number of available free registers, returns 1061 /// true if any registers were allocated. 1062 bool updateFreeRegs(QualType Ty, CCState &State) const; 1063 1064 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg, 1065 bool &NeedsPadding) const; 1066 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const; 1067 1068 bool canExpandIndirectArgument(QualType Ty) const; 1069 1070 /// Rewrite the function info so that all memory arguments use 1071 /// inalloca. 1072 void rewriteWithInAlloca(CGFunctionInfo &FI) const; 1073 1074 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1075 CharUnits &StackOffset, ABIArgInfo &Info, 1076 QualType Type) const; 1077 void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const; 1078 1079 public: 1080 1081 void computeInfo(CGFunctionInfo &FI) const override; 1082 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 1083 QualType Ty) const override; 1084 1085 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1086 bool RetSmallStructInRegABI, bool Win32StructABI, 1087 unsigned NumRegisterParameters, bool SoftFloatABI) 1088 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI), 1089 IsRetSmallStructInRegABI(RetSmallStructInRegABI), 1090 IsWin32StructABI(Win32StructABI), 1091 IsSoftFloatABI(SoftFloatABI), 1092 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()), 1093 DefaultNumRegisterParameters(NumRegisterParameters) {} 1094 1095 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 1096 bool asReturnValue) const override { 1097 // LLVM's x86-32 lowering currently only assigns up to three 1098 // integer registers and three fp registers. Oddly, it'll use up to 1099 // four vector registers for vectors, but those can overlap with the 1100 // scalar registers. 1101 return occupiesMoreThan(CGT, scalars, /*total*/ 3); 1102 } 1103 1104 bool isSwiftErrorInRegister() const override { 1105 // x86-32 lowering does not support passing swifterror in a register. 1106 return false; 1107 } 1108 }; 1109 1110 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { 1111 public: 1112 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1113 bool RetSmallStructInRegABI, bool Win32StructABI, 1114 unsigned NumRegisterParameters, bool SoftFloatABI) 1115 : TargetCodeGenInfo(new X86_32ABIInfo( 1116 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI, 1117 NumRegisterParameters, SoftFloatABI)) {} 1118 1119 static bool isStructReturnInRegABI( 1120 const llvm::Triple &Triple, const CodeGenOptions &Opts); 1121 1122 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 1123 CodeGen::CodeGenModule &CGM) const override; 1124 1125 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 1126 // Darwin uses different dwarf register numbers for EH. 1127 if (CGM.getTarget().getTriple().isOSDarwin()) return 5; 1128 return 4; 1129 } 1130 1131 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1132 llvm::Value *Address) const override; 1133 1134 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1135 StringRef Constraint, 1136 llvm::Type* Ty) const override { 1137 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 1138 } 1139 1140 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue, 1141 std::string &Constraints, 1142 std::vector<llvm::Type *> &ResultRegTypes, 1143 std::vector<llvm::Type *> &ResultTruncRegTypes, 1144 std::vector<LValue> &ResultRegDests, 1145 std::string &AsmString, 1146 unsigned NumOutputs) const override; 1147 1148 llvm::Constant * 1149 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 1150 unsigned Sig = (0xeb << 0) | // jmp rel8 1151 (0x06 << 8) | // .+0x08 1152 ('v' << 16) | 1153 ('2' << 24); 1154 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 1155 } 1156 1157 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 1158 return "movl\t%ebp, %ebp" 1159 "\t\t// marker for objc_retainAutoreleaseReturnValue"; 1160 } 1161 }; 1162 1163 } 1164 1165 /// Rewrite input constraint references after adding some output constraints. 1166 /// In the case where there is one output and one input and we add one output, 1167 /// we need to replace all operand references greater than or equal to 1: 1168 /// mov $0, $1 1169 /// mov eax, $1 1170 /// The result will be: 1171 /// mov $0, $2 1172 /// mov eax, $2 1173 static void rewriteInputConstraintReferences(unsigned FirstIn, 1174 unsigned NumNewOuts, 1175 std::string &AsmString) { 1176 std::string Buf; 1177 llvm::raw_string_ostream OS(Buf); 1178 size_t Pos = 0; 1179 while (Pos < AsmString.size()) { 1180 size_t DollarStart = AsmString.find('$', Pos); 1181 if (DollarStart == std::string::npos) 1182 DollarStart = AsmString.size(); 1183 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart); 1184 if (DollarEnd == std::string::npos) 1185 DollarEnd = AsmString.size(); 1186 OS << StringRef(&AsmString[Pos], DollarEnd - Pos); 1187 Pos = DollarEnd; 1188 size_t NumDollars = DollarEnd - DollarStart; 1189 if (NumDollars % 2 != 0 && Pos < AsmString.size()) { 1190 // We have an operand reference. 1191 size_t DigitStart = Pos; 1192 if (AsmString[DigitStart] == '{') { 1193 OS << '{'; 1194 ++DigitStart; 1195 } 1196 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart); 1197 if (DigitEnd == std::string::npos) 1198 DigitEnd = AsmString.size(); 1199 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart); 1200 unsigned OperandIndex; 1201 if (!OperandStr.getAsInteger(10, OperandIndex)) { 1202 if (OperandIndex >= FirstIn) 1203 OperandIndex += NumNewOuts; 1204 OS << OperandIndex; 1205 } else { 1206 OS << OperandStr; 1207 } 1208 Pos = DigitEnd; 1209 } 1210 } 1211 AsmString = std::move(OS.str()); 1212 } 1213 1214 /// Add output constraints for EAX:EDX because they are return registers. 1215 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs( 1216 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints, 1217 std::vector<llvm::Type *> &ResultRegTypes, 1218 std::vector<llvm::Type *> &ResultTruncRegTypes, 1219 std::vector<LValue> &ResultRegDests, std::string &AsmString, 1220 unsigned NumOutputs) const { 1221 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType()); 1222 1223 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is 1224 // larger. 1225 if (!Constraints.empty()) 1226 Constraints += ','; 1227 if (RetWidth <= 32) { 1228 Constraints += "={eax}"; 1229 ResultRegTypes.push_back(CGF.Int32Ty); 1230 } else { 1231 // Use the 'A' constraint for EAX:EDX. 1232 Constraints += "=A"; 1233 ResultRegTypes.push_back(CGF.Int64Ty); 1234 } 1235 1236 // Truncate EAX or EAX:EDX to an integer of the appropriate size. 1237 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth); 1238 ResultTruncRegTypes.push_back(CoerceTy); 1239 1240 // Coerce the integer by bitcasting the return slot pointer. 1241 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF), 1242 CoerceTy->getPointerTo())); 1243 ResultRegDests.push_back(ReturnSlot); 1244 1245 rewriteInputConstraintReferences(NumOutputs, 1, AsmString); 1246 } 1247 1248 /// shouldReturnTypeInRegister - Determine if the given type should be 1249 /// returned in a register (for the Darwin and MCU ABI). 1250 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, 1251 ASTContext &Context) const { 1252 uint64_t Size = Context.getTypeSize(Ty); 1253 1254 // For i386, type must be register sized. 1255 // For the MCU ABI, it only needs to be <= 8-byte 1256 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size))) 1257 return false; 1258 1259 if (Ty->isVectorType()) { 1260 // 64- and 128- bit vectors inside structures are not returned in 1261 // registers. 1262 if (Size == 64 || Size == 128) 1263 return false; 1264 1265 return true; 1266 } 1267 1268 // If this is a builtin, pointer, enum, complex type, member pointer, or 1269 // member function pointer it is ok. 1270 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() || 1271 Ty->isAnyComplexType() || Ty->isEnumeralType() || 1272 Ty->isBlockPointerType() || Ty->isMemberPointerType()) 1273 return true; 1274 1275 // Arrays are treated like records. 1276 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) 1277 return shouldReturnTypeInRegister(AT->getElementType(), Context); 1278 1279 // Otherwise, it must be a record type. 1280 const RecordType *RT = Ty->getAs<RecordType>(); 1281 if (!RT) return false; 1282 1283 // FIXME: Traverse bases here too. 1284 1285 // Structure types are passed in register if all fields would be 1286 // passed in a register. 1287 for (const auto *FD : RT->getDecl()->fields()) { 1288 // Empty fields are ignored. 1289 if (isEmptyField(Context, FD, true)) 1290 continue; 1291 1292 // Check fields recursively. 1293 if (!shouldReturnTypeInRegister(FD->getType(), Context)) 1294 return false; 1295 } 1296 return true; 1297 } 1298 1299 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { 1300 // Treat complex types as the element type. 1301 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 1302 Ty = CTy->getElementType(); 1303 1304 // Check for a type which we know has a simple scalar argument-passing 1305 // convention without any padding. (We're specifically looking for 32 1306 // and 64-bit integer and integer-equivalents, float, and double.) 1307 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() && 1308 !Ty->isEnumeralType() && !Ty->isBlockPointerType()) 1309 return false; 1310 1311 uint64_t Size = Context.getTypeSize(Ty); 1312 return Size == 32 || Size == 64; 1313 } 1314 1315 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD, 1316 uint64_t &Size) { 1317 for (const auto *FD : RD->fields()) { 1318 // Scalar arguments on the stack get 4 byte alignment on x86. If the 1319 // argument is smaller than 32-bits, expanding the struct will create 1320 // alignment padding. 1321 if (!is32Or64BitBasicType(FD->getType(), Context)) 1322 return false; 1323 1324 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know 1325 // how to expand them yet, and the predicate for telling if a bitfield still 1326 // counts as "basic" is more complicated than what we were doing previously. 1327 if (FD->isBitField()) 1328 return false; 1329 1330 Size += Context.getTypeSize(FD->getType()); 1331 } 1332 return true; 1333 } 1334 1335 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD, 1336 uint64_t &Size) { 1337 // Don't do this if there are any non-empty bases. 1338 for (const CXXBaseSpecifier &Base : RD->bases()) { 1339 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(), 1340 Size)) 1341 return false; 1342 } 1343 if (!addFieldSizes(Context, RD, Size)) 1344 return false; 1345 return true; 1346 } 1347 1348 /// Test whether an argument type which is to be passed indirectly (on the 1349 /// stack) would have the equivalent layout if it was expanded into separate 1350 /// arguments. If so, we prefer to do the latter to avoid inhibiting 1351 /// optimizations. 1352 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const { 1353 // We can only expand structure types. 1354 const RecordType *RT = Ty->getAs<RecordType>(); 1355 if (!RT) 1356 return false; 1357 const RecordDecl *RD = RT->getDecl(); 1358 uint64_t Size = 0; 1359 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1360 if (!IsWin32StructABI) { 1361 // On non-Windows, we have to conservatively match our old bitcode 1362 // prototypes in order to be ABI-compatible at the bitcode level. 1363 if (!CXXRD->isCLike()) 1364 return false; 1365 } else { 1366 // Don't do this for dynamic classes. 1367 if (CXXRD->isDynamicClass()) 1368 return false; 1369 } 1370 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size)) 1371 return false; 1372 } else { 1373 if (!addFieldSizes(getContext(), RD, Size)) 1374 return false; 1375 } 1376 1377 // We can do this if there was no alignment padding. 1378 return Size == getContext().getTypeSize(Ty); 1379 } 1380 1381 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const { 1382 // If the return value is indirect, then the hidden argument is consuming one 1383 // integer register. 1384 if (State.FreeRegs) { 1385 --State.FreeRegs; 1386 if (!IsMCUABI) 1387 return getNaturalAlignIndirectInReg(RetTy); 1388 } 1389 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 1390 } 1391 1392 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, 1393 CCState &State) const { 1394 if (RetTy->isVoidType()) 1395 return ABIArgInfo::getIgnore(); 1396 1397 const Type *Base = nullptr; 1398 uint64_t NumElts = 0; 1399 if ((State.CC == llvm::CallingConv::X86_VectorCall || 1400 State.CC == llvm::CallingConv::X86_RegCall) && 1401 isHomogeneousAggregate(RetTy, Base, NumElts)) { 1402 // The LLVM struct type for such an aggregate should lower properly. 1403 return ABIArgInfo::getDirect(); 1404 } 1405 1406 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 1407 // On Darwin, some vectors are returned in registers. 1408 if (IsDarwinVectorABI) { 1409 uint64_t Size = getContext().getTypeSize(RetTy); 1410 1411 // 128-bit vectors are a special case; they are returned in 1412 // registers and we need to make sure to pick a type the LLVM 1413 // backend will like. 1414 if (Size == 128) 1415 return ABIArgInfo::getDirect(llvm::VectorType::get( 1416 llvm::Type::getInt64Ty(getVMContext()), 2)); 1417 1418 // Always return in register if it fits in a general purpose 1419 // register, or if it is 64 bits and has a single element. 1420 if ((Size == 8 || Size == 16 || Size == 32) || 1421 (Size == 64 && VT->getNumElements() == 1)) 1422 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 1423 Size)); 1424 1425 return getIndirectReturnResult(RetTy, State); 1426 } 1427 1428 return ABIArgInfo::getDirect(); 1429 } 1430 1431 if (isAggregateTypeForABI(RetTy)) { 1432 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 1433 // Structures with flexible arrays are always indirect. 1434 if (RT->getDecl()->hasFlexibleArrayMember()) 1435 return getIndirectReturnResult(RetTy, State); 1436 } 1437 1438 // If specified, structs and unions are always indirect. 1439 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType()) 1440 return getIndirectReturnResult(RetTy, State); 1441 1442 // Ignore empty structs/unions. 1443 if (isEmptyRecord(getContext(), RetTy, true)) 1444 return ABIArgInfo::getIgnore(); 1445 1446 // Small structures which are register sized are generally returned 1447 // in a register. 1448 if (shouldReturnTypeInRegister(RetTy, getContext())) { 1449 uint64_t Size = getContext().getTypeSize(RetTy); 1450 1451 // As a special-case, if the struct is a "single-element" struct, and 1452 // the field is of type "float" or "double", return it in a 1453 // floating-point register. (MSVC does not apply this special case.) 1454 // We apply a similar transformation for pointer types to improve the 1455 // quality of the generated IR. 1456 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 1457 if ((!IsWin32StructABI && SeltTy->isRealFloatingType()) 1458 || SeltTy->hasPointerRepresentation()) 1459 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 1460 1461 // FIXME: We should be able to narrow this integer in cases with dead 1462 // padding. 1463 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); 1464 } 1465 1466 return getIndirectReturnResult(RetTy, State); 1467 } 1468 1469 // Treat an enum type as its underlying type. 1470 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1471 RetTy = EnumTy->getDecl()->getIntegerType(); 1472 1473 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 1474 : ABIArgInfo::getDirect()); 1475 } 1476 1477 static bool isSSEVectorType(ASTContext &Context, QualType Ty) { 1478 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128; 1479 } 1480 1481 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) { 1482 const RecordType *RT = Ty->getAs<RecordType>(); 1483 if (!RT) 1484 return 0; 1485 const RecordDecl *RD = RT->getDecl(); 1486 1487 // If this is a C++ record, check the bases first. 1488 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1489 for (const auto &I : CXXRD->bases()) 1490 if (!isRecordWithSSEVectorType(Context, I.getType())) 1491 return false; 1492 1493 for (const auto *i : RD->fields()) { 1494 QualType FT = i->getType(); 1495 1496 if (isSSEVectorType(Context, FT)) 1497 return true; 1498 1499 if (isRecordWithSSEVectorType(Context, FT)) 1500 return true; 1501 } 1502 1503 return false; 1504 } 1505 1506 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, 1507 unsigned Align) const { 1508 // Otherwise, if the alignment is less than or equal to the minimum ABI 1509 // alignment, just use the default; the backend will handle this. 1510 if (Align <= MinABIStackAlignInBytes) 1511 return 0; // Use default alignment. 1512 1513 // On non-Darwin, the stack type alignment is always 4. 1514 if (!IsDarwinVectorABI) { 1515 // Set explicit alignment, since we may need to realign the top. 1516 return MinABIStackAlignInBytes; 1517 } 1518 1519 // Otherwise, if the type contains an SSE vector type, the alignment is 16. 1520 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) || 1521 isRecordWithSSEVectorType(getContext(), Ty))) 1522 return 16; 1523 1524 return MinABIStackAlignInBytes; 1525 } 1526 1527 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal, 1528 CCState &State) const { 1529 if (!ByVal) { 1530 if (State.FreeRegs) { 1531 --State.FreeRegs; // Non-byval indirects just use one pointer. 1532 if (!IsMCUABI) 1533 return getNaturalAlignIndirectInReg(Ty); 1534 } 1535 return getNaturalAlignIndirect(Ty, false); 1536 } 1537 1538 // Compute the byval alignment. 1539 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 1540 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); 1541 if (StackAlign == 0) 1542 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true); 1543 1544 // If the stack alignment is less than the type alignment, realign the 1545 // argument. 1546 bool Realign = TypeAlign > StackAlign; 1547 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign), 1548 /*ByVal=*/true, Realign); 1549 } 1550 1551 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const { 1552 const Type *T = isSingleElementStruct(Ty, getContext()); 1553 if (!T) 1554 T = Ty.getTypePtr(); 1555 1556 if (const BuiltinType *BT = T->getAs<BuiltinType>()) { 1557 BuiltinType::Kind K = BT->getKind(); 1558 if (K == BuiltinType::Float || K == BuiltinType::Double) 1559 return Float; 1560 } 1561 return Integer; 1562 } 1563 1564 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const { 1565 if (!IsSoftFloatABI) { 1566 Class C = classify(Ty); 1567 if (C == Float) 1568 return false; 1569 } 1570 1571 unsigned Size = getContext().getTypeSize(Ty); 1572 unsigned SizeInRegs = (Size + 31) / 32; 1573 1574 if (SizeInRegs == 0) 1575 return false; 1576 1577 if (!IsMCUABI) { 1578 if (SizeInRegs > State.FreeRegs) { 1579 State.FreeRegs = 0; 1580 return false; 1581 } 1582 } else { 1583 // The MCU psABI allows passing parameters in-reg even if there are 1584 // earlier parameters that are passed on the stack. Also, 1585 // it does not allow passing >8-byte structs in-register, 1586 // even if there are 3 free registers available. 1587 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2) 1588 return false; 1589 } 1590 1591 State.FreeRegs -= SizeInRegs; 1592 return true; 1593 } 1594 1595 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State, 1596 bool &InReg, 1597 bool &NeedsPadding) const { 1598 // On Windows, aggregates other than HFAs are never passed in registers, and 1599 // they do not consume register slots. Homogenous floating-point aggregates 1600 // (HFAs) have already been dealt with at this point. 1601 if (IsWin32StructABI && isAggregateTypeForABI(Ty)) 1602 return false; 1603 1604 NeedsPadding = false; 1605 InReg = !IsMCUABI; 1606 1607 if (!updateFreeRegs(Ty, State)) 1608 return false; 1609 1610 if (IsMCUABI) 1611 return true; 1612 1613 if (State.CC == llvm::CallingConv::X86_FastCall || 1614 State.CC == llvm::CallingConv::X86_VectorCall || 1615 State.CC == llvm::CallingConv::X86_RegCall) { 1616 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs) 1617 NeedsPadding = true; 1618 1619 return false; 1620 } 1621 1622 return true; 1623 } 1624 1625 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const { 1626 if (!updateFreeRegs(Ty, State)) 1627 return false; 1628 1629 if (IsMCUABI) 1630 return false; 1631 1632 if (State.CC == llvm::CallingConv::X86_FastCall || 1633 State.CC == llvm::CallingConv::X86_VectorCall || 1634 State.CC == llvm::CallingConv::X86_RegCall) { 1635 if (getContext().getTypeSize(Ty) > 32) 1636 return false; 1637 1638 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() || 1639 Ty->isReferenceType()); 1640 } 1641 1642 return true; 1643 } 1644 1645 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const { 1646 // Vectorcall x86 works subtly different than in x64, so the format is 1647 // a bit different than the x64 version. First, all vector types (not HVAs) 1648 // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers. 1649 // This differs from the x64 implementation, where the first 6 by INDEX get 1650 // registers. 1651 // In the second pass over the arguments, HVAs are passed in the remaining 1652 // vector registers if possible, or indirectly by address. The address will be 1653 // passed in ECX/EDX if available. Any other arguments are passed according to 1654 // the usual fastcall rules. 1655 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1656 for (int I = 0, E = Args.size(); I < E; ++I) { 1657 const Type *Base = nullptr; 1658 uint64_t NumElts = 0; 1659 const QualType &Ty = Args[I].type; 1660 if ((Ty->isVectorType() || Ty->isBuiltinType()) && 1661 isHomogeneousAggregate(Ty, Base, NumElts)) { 1662 if (State.FreeSSERegs >= NumElts) { 1663 State.FreeSSERegs -= NumElts; 1664 Args[I].info = ABIArgInfo::getDirect(); 1665 State.IsPreassigned.set(I); 1666 } 1667 } 1668 } 1669 } 1670 1671 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, 1672 CCState &State) const { 1673 // FIXME: Set alignment on indirect arguments. 1674 bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall; 1675 bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall; 1676 bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall; 1677 1678 Ty = useFirstFieldIfTransparentUnion(Ty); 1679 1680 // Check with the C++ ABI first. 1681 const RecordType *RT = Ty->getAs<RecordType>(); 1682 if (RT) { 1683 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 1684 if (RAA == CGCXXABI::RAA_Indirect) { 1685 return getIndirectResult(Ty, false, State); 1686 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 1687 // The field index doesn't matter, we'll fix it up later. 1688 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0); 1689 } 1690 } 1691 1692 // Regcall uses the concept of a homogenous vector aggregate, similar 1693 // to other targets. 1694 const Type *Base = nullptr; 1695 uint64_t NumElts = 0; 1696 if ((IsRegCall || IsVectorCall) && 1697 isHomogeneousAggregate(Ty, Base, NumElts)) { 1698 if (State.FreeSSERegs >= NumElts) { 1699 State.FreeSSERegs -= NumElts; 1700 1701 // Vectorcall passes HVAs directly and does not flatten them, but regcall 1702 // does. 1703 if (IsVectorCall) 1704 return getDirectX86Hva(); 1705 1706 if (Ty->isBuiltinType() || Ty->isVectorType()) 1707 return ABIArgInfo::getDirect(); 1708 return ABIArgInfo::getExpand(); 1709 } 1710 return getIndirectResult(Ty, /*ByVal=*/false, State); 1711 } 1712 1713 if (isAggregateTypeForABI(Ty)) { 1714 // Structures with flexible arrays are always indirect. 1715 // FIXME: This should not be byval! 1716 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 1717 return getIndirectResult(Ty, true, State); 1718 1719 // Ignore empty structs/unions on non-Windows. 1720 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true)) 1721 return ABIArgInfo::getIgnore(); 1722 1723 llvm::LLVMContext &LLVMContext = getVMContext(); 1724 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 1725 bool NeedsPadding = false; 1726 bool InReg; 1727 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) { 1728 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 1729 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32); 1730 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 1731 if (InReg) 1732 return ABIArgInfo::getDirectInReg(Result); 1733 else 1734 return ABIArgInfo::getDirect(Result); 1735 } 1736 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr; 1737 1738 // Expand small (<= 128-bit) record types when we know that the stack layout 1739 // of those arguments will match the struct. This is important because the 1740 // LLVM backend isn't smart enough to remove byval, which inhibits many 1741 // optimizations. 1742 // Don't do this for the MCU if there are still free integer registers 1743 // (see X86_64 ABI for full explanation). 1744 if (getContext().getTypeSize(Ty) <= 4 * 32 && 1745 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty)) 1746 return ABIArgInfo::getExpandWithPadding( 1747 IsFastCall || IsVectorCall || IsRegCall, PaddingType); 1748 1749 return getIndirectResult(Ty, true, State); 1750 } 1751 1752 if (const VectorType *VT = Ty->getAs<VectorType>()) { 1753 // On Darwin, some vectors are passed in memory, we handle this by passing 1754 // it as an i8/i16/i32/i64. 1755 if (IsDarwinVectorABI) { 1756 uint64_t Size = getContext().getTypeSize(Ty); 1757 if ((Size == 8 || Size == 16 || Size == 32) || 1758 (Size == 64 && VT->getNumElements() == 1)) 1759 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 1760 Size)); 1761 } 1762 1763 if (IsX86_MMXType(CGT.ConvertType(Ty))) 1764 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64)); 1765 1766 return ABIArgInfo::getDirect(); 1767 } 1768 1769 1770 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1771 Ty = EnumTy->getDecl()->getIntegerType(); 1772 1773 bool InReg = shouldPrimitiveUseInReg(Ty, State); 1774 1775 if (Ty->isPromotableIntegerType()) { 1776 if (InReg) 1777 return ABIArgInfo::getExtendInReg(Ty); 1778 return ABIArgInfo::getExtend(Ty); 1779 } 1780 1781 if (InReg) 1782 return ABIArgInfo::getDirectInReg(); 1783 return ABIArgInfo::getDirect(); 1784 } 1785 1786 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const { 1787 CCState State(FI); 1788 if (IsMCUABI) 1789 State.FreeRegs = 3; 1790 else if (State.CC == llvm::CallingConv::X86_FastCall) 1791 State.FreeRegs = 2; 1792 else if (State.CC == llvm::CallingConv::X86_VectorCall) { 1793 State.FreeRegs = 2; 1794 State.FreeSSERegs = 6; 1795 } else if (FI.getHasRegParm()) 1796 State.FreeRegs = FI.getRegParm(); 1797 else if (State.CC == llvm::CallingConv::X86_RegCall) { 1798 State.FreeRegs = 5; 1799 State.FreeSSERegs = 8; 1800 } else 1801 State.FreeRegs = DefaultNumRegisterParameters; 1802 1803 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 1804 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State); 1805 } else if (FI.getReturnInfo().isIndirect()) { 1806 // The C++ ABI is not aware of register usage, so we have to check if the 1807 // return value was sret and put it in a register ourselves if appropriate. 1808 if (State.FreeRegs) { 1809 --State.FreeRegs; // The sret parameter consumes a register. 1810 if (!IsMCUABI) 1811 FI.getReturnInfo().setInReg(true); 1812 } 1813 } 1814 1815 // The chain argument effectively gives us another free register. 1816 if (FI.isChainCall()) 1817 ++State.FreeRegs; 1818 1819 // For vectorcall, do a first pass over the arguments, assigning FP and vector 1820 // arguments to XMM registers as available. 1821 if (State.CC == llvm::CallingConv::X86_VectorCall) 1822 runVectorCallFirstPass(FI, State); 1823 1824 bool UsedInAlloca = false; 1825 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1826 for (int I = 0, E = Args.size(); I < E; ++I) { 1827 // Skip arguments that have already been assigned. 1828 if (State.IsPreassigned.test(I)) 1829 continue; 1830 1831 Args[I].info = classifyArgumentType(Args[I].type, State); 1832 UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca); 1833 } 1834 1835 // If we needed to use inalloca for any argument, do a second pass and rewrite 1836 // all the memory arguments to use inalloca. 1837 if (UsedInAlloca) 1838 rewriteWithInAlloca(FI); 1839 } 1840 1841 void 1842 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1843 CharUnits &StackOffset, ABIArgInfo &Info, 1844 QualType Type) const { 1845 // Arguments are always 4-byte-aligned. 1846 CharUnits FieldAlign = CharUnits::fromQuantity(4); 1847 1848 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct"); 1849 Info = ABIArgInfo::getInAlloca(FrameFields.size()); 1850 FrameFields.push_back(CGT.ConvertTypeForMem(Type)); 1851 StackOffset += getContext().getTypeSizeInChars(Type); 1852 1853 // Insert padding bytes to respect alignment. 1854 CharUnits FieldEnd = StackOffset; 1855 StackOffset = FieldEnd.alignTo(FieldAlign); 1856 if (StackOffset != FieldEnd) { 1857 CharUnits NumBytes = StackOffset - FieldEnd; 1858 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext()); 1859 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity()); 1860 FrameFields.push_back(Ty); 1861 } 1862 } 1863 1864 static bool isArgInAlloca(const ABIArgInfo &Info) { 1865 // Leave ignored and inreg arguments alone. 1866 switch (Info.getKind()) { 1867 case ABIArgInfo::InAlloca: 1868 return true; 1869 case ABIArgInfo::Indirect: 1870 assert(Info.getIndirectByVal()); 1871 return true; 1872 case ABIArgInfo::Ignore: 1873 return false; 1874 case ABIArgInfo::Direct: 1875 case ABIArgInfo::Extend: 1876 if (Info.getInReg()) 1877 return false; 1878 return true; 1879 case ABIArgInfo::Expand: 1880 case ABIArgInfo::CoerceAndExpand: 1881 // These are aggregate types which are never passed in registers when 1882 // inalloca is involved. 1883 return true; 1884 } 1885 llvm_unreachable("invalid enum"); 1886 } 1887 1888 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const { 1889 assert(IsWin32StructABI && "inalloca only supported on win32"); 1890 1891 // Build a packed struct type for all of the arguments in memory. 1892 SmallVector<llvm::Type *, 6> FrameFields; 1893 1894 // The stack alignment is always 4. 1895 CharUnits StackAlign = CharUnits::fromQuantity(4); 1896 1897 CharUnits StackOffset; 1898 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end(); 1899 1900 // Put 'this' into the struct before 'sret', if necessary. 1901 bool IsThisCall = 1902 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall; 1903 ABIArgInfo &Ret = FI.getReturnInfo(); 1904 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall && 1905 isArgInAlloca(I->info)) { 1906 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 1907 ++I; 1908 } 1909 1910 // Put the sret parameter into the inalloca struct if it's in memory. 1911 if (Ret.isIndirect() && !Ret.getInReg()) { 1912 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType()); 1913 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy); 1914 // On Windows, the hidden sret parameter is always returned in eax. 1915 Ret.setInAllocaSRet(IsWin32StructABI); 1916 } 1917 1918 // Skip the 'this' parameter in ecx. 1919 if (IsThisCall) 1920 ++I; 1921 1922 // Put arguments passed in memory into the struct. 1923 for (; I != E; ++I) { 1924 if (isArgInAlloca(I->info)) 1925 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 1926 } 1927 1928 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields, 1929 /*isPacked=*/true), 1930 StackAlign); 1931 } 1932 1933 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF, 1934 Address VAListAddr, QualType Ty) const { 1935 1936 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 1937 1938 // x86-32 changes the alignment of certain arguments on the stack. 1939 // 1940 // Just messing with TypeInfo like this works because we never pass 1941 // anything indirectly. 1942 TypeInfo.second = CharUnits::fromQuantity( 1943 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity())); 1944 1945 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 1946 TypeInfo, CharUnits::fromQuantity(4), 1947 /*AllowHigherAlign*/ true); 1948 } 1949 1950 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI( 1951 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 1952 assert(Triple.getArch() == llvm::Triple::x86); 1953 1954 switch (Opts.getStructReturnConvention()) { 1955 case CodeGenOptions::SRCK_Default: 1956 break; 1957 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return 1958 return false; 1959 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return 1960 return true; 1961 } 1962 1963 if (Triple.isOSDarwin() || Triple.isOSIAMCU()) 1964 return true; 1965 1966 switch (Triple.getOS()) { 1967 case llvm::Triple::DragonFly: 1968 case llvm::Triple::FreeBSD: 1969 case llvm::Triple::OpenBSD: 1970 case llvm::Triple::Win32: 1971 return true; 1972 default: 1973 return false; 1974 } 1975 } 1976 1977 void X86_32TargetCodeGenInfo::setTargetAttributes( 1978 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 1979 if (GV->isDeclaration()) 1980 return; 1981 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 1982 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 1983 llvm::Function *Fn = cast<llvm::Function>(GV); 1984 Fn->addFnAttr("stackrealign"); 1985 } 1986 if (FD->hasAttr<AnyX86InterruptAttr>()) { 1987 llvm::Function *Fn = cast<llvm::Function>(GV); 1988 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 1989 } 1990 } 1991 } 1992 1993 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( 1994 CodeGen::CodeGenFunction &CGF, 1995 llvm::Value *Address) const { 1996 CodeGen::CGBuilderTy &Builder = CGF.Builder; 1997 1998 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 1999 2000 // 0-7 are the eight integer registers; the order is different 2001 // on Darwin (for EH), but the range is the same. 2002 // 8 is %eip. 2003 AssignToArrayRange(Builder, Address, Four8, 0, 8); 2004 2005 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) { 2006 // 12-16 are st(0..4). Not sure why we stop at 4. 2007 // These have size 16, which is sizeof(long double) on 2008 // platforms with 8-byte alignment for that type. 2009 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 2010 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); 2011 2012 } else { 2013 // 9 is %eflags, which doesn't get a size on Darwin for some 2014 // reason. 2015 Builder.CreateAlignedStore( 2016 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9), 2017 CharUnits::One()); 2018 2019 // 11-16 are st(0..5). Not sure why we stop at 5. 2020 // These have size 12, which is sizeof(long double) on 2021 // platforms with 4-byte alignment for that type. 2022 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); 2023 AssignToArrayRange(Builder, Address, Twelve8, 11, 16); 2024 } 2025 2026 return false; 2027 } 2028 2029 //===----------------------------------------------------------------------===// 2030 // X86-64 ABI Implementation 2031 //===----------------------------------------------------------------------===// 2032 2033 2034 namespace { 2035 /// The AVX ABI level for X86 targets. 2036 enum class X86AVXABILevel { 2037 None, 2038 AVX, 2039 AVX512 2040 }; 2041 2042 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel. 2043 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) { 2044 switch (AVXLevel) { 2045 case X86AVXABILevel::AVX512: 2046 return 512; 2047 case X86AVXABILevel::AVX: 2048 return 256; 2049 case X86AVXABILevel::None: 2050 return 128; 2051 } 2052 llvm_unreachable("Unknown AVXLevel"); 2053 } 2054 2055 /// X86_64ABIInfo - The X86_64 ABI information. 2056 class X86_64ABIInfo : public SwiftABIInfo { 2057 enum Class { 2058 Integer = 0, 2059 SSE, 2060 SSEUp, 2061 X87, 2062 X87Up, 2063 ComplexX87, 2064 NoClass, 2065 Memory 2066 }; 2067 2068 /// merge - Implement the X86_64 ABI merging algorithm. 2069 /// 2070 /// Merge an accumulating classification \arg Accum with a field 2071 /// classification \arg Field. 2072 /// 2073 /// \param Accum - The accumulating classification. This should 2074 /// always be either NoClass or the result of a previous merge 2075 /// call. In addition, this should never be Memory (the caller 2076 /// should just return Memory for the aggregate). 2077 static Class merge(Class Accum, Class Field); 2078 2079 /// postMerge - Implement the X86_64 ABI post merging algorithm. 2080 /// 2081 /// Post merger cleanup, reduces a malformed Hi and Lo pair to 2082 /// final MEMORY or SSE classes when necessary. 2083 /// 2084 /// \param AggregateSize - The size of the current aggregate in 2085 /// the classification process. 2086 /// 2087 /// \param Lo - The classification for the parts of the type 2088 /// residing in the low word of the containing object. 2089 /// 2090 /// \param Hi - The classification for the parts of the type 2091 /// residing in the higher words of the containing object. 2092 /// 2093 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; 2094 2095 /// classify - Determine the x86_64 register classes in which the 2096 /// given type T should be passed. 2097 /// 2098 /// \param Lo - The classification for the parts of the type 2099 /// residing in the low word of the containing object. 2100 /// 2101 /// \param Hi - The classification for the parts of the type 2102 /// residing in the high word of the containing object. 2103 /// 2104 /// \param OffsetBase - The bit offset of this type in the 2105 /// containing object. Some parameters are classified different 2106 /// depending on whether they straddle an eightbyte boundary. 2107 /// 2108 /// \param isNamedArg - Whether the argument in question is a "named" 2109 /// argument, as used in AMD64-ABI 3.5.7. 2110 /// 2111 /// If a word is unused its result will be NoClass; if a type should 2112 /// be passed in Memory then at least the classification of \arg Lo 2113 /// will be Memory. 2114 /// 2115 /// The \arg Lo class will be NoClass iff the argument is ignored. 2116 /// 2117 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will 2118 /// also be ComplexX87. 2119 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi, 2120 bool isNamedArg) const; 2121 2122 llvm::Type *GetByteVectorType(QualType Ty) const; 2123 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, 2124 unsigned IROffset, QualType SourceTy, 2125 unsigned SourceOffset) const; 2126 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, 2127 unsigned IROffset, QualType SourceTy, 2128 unsigned SourceOffset) const; 2129 2130 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2131 /// such that the argument will be returned in memory. 2132 ABIArgInfo getIndirectReturnResult(QualType Ty) const; 2133 2134 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2135 /// such that the argument will be passed in memory. 2136 /// 2137 /// \param freeIntRegs - The number of free integer registers remaining 2138 /// available. 2139 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const; 2140 2141 ABIArgInfo classifyReturnType(QualType RetTy) const; 2142 2143 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs, 2144 unsigned &neededInt, unsigned &neededSSE, 2145 bool isNamedArg) const; 2146 2147 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt, 2148 unsigned &NeededSSE) const; 2149 2150 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 2151 unsigned &NeededSSE) const; 2152 2153 bool IsIllegalVectorType(QualType Ty) const; 2154 2155 /// The 0.98 ABI revision clarified a lot of ambiguities, 2156 /// unfortunately in ways that were not always consistent with 2157 /// certain previous compilers. In particular, platforms which 2158 /// required strict binary compatibility with older versions of GCC 2159 /// may need to exempt themselves. 2160 bool honorsRevision0_98() const { 2161 return !getTarget().getTriple().isOSDarwin(); 2162 } 2163 2164 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to 2165 /// classify it as INTEGER (for compatibility with older clang compilers). 2166 bool classifyIntegerMMXAsSSE() const { 2167 // Clang <= 3.8 did not do this. 2168 if (getContext().getLangOpts().getClangABICompat() <= 2169 LangOptions::ClangABI::Ver3_8) 2170 return false; 2171 2172 const llvm::Triple &Triple = getTarget().getTriple(); 2173 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4) 2174 return false; 2175 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10) 2176 return false; 2177 return true; 2178 } 2179 2180 // GCC classifies vectors of __int128 as memory. 2181 bool passInt128VectorsInMem() const { 2182 // Clang <= 9.0 did not do this. 2183 if (getContext().getLangOpts().getClangABICompat() <= 2184 LangOptions::ClangABI::Ver9) 2185 return false; 2186 2187 const llvm::Triple &T = getTarget().getTriple(); 2188 return T.isOSLinux() || T.isOSNetBSD(); 2189 } 2190 2191 X86AVXABILevel AVXLevel; 2192 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on 2193 // 64-bit hardware. 2194 bool Has64BitPointers; 2195 2196 public: 2197 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) : 2198 SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2199 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) { 2200 } 2201 2202 bool isPassedUsingAVXType(QualType type) const { 2203 unsigned neededInt, neededSSE; 2204 // The freeIntRegs argument doesn't matter here. 2205 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE, 2206 /*isNamedArg*/true); 2207 if (info.isDirect()) { 2208 llvm::Type *ty = info.getCoerceToType(); 2209 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty)) 2210 return (vectorTy->getBitWidth() > 128); 2211 } 2212 return false; 2213 } 2214 2215 void computeInfo(CGFunctionInfo &FI) const override; 2216 2217 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2218 QualType Ty) const override; 2219 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 2220 QualType Ty) const override; 2221 2222 bool has64BitPointers() const { 2223 return Has64BitPointers; 2224 } 2225 2226 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 2227 bool asReturnValue) const override { 2228 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2229 } 2230 bool isSwiftErrorInRegister() const override { 2231 return true; 2232 } 2233 }; 2234 2235 /// WinX86_64ABIInfo - The Windows X86_64 ABI information. 2236 class WinX86_64ABIInfo : public SwiftABIInfo { 2237 public: 2238 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2239 : SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2240 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {} 2241 2242 void computeInfo(CGFunctionInfo &FI) const override; 2243 2244 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2245 QualType Ty) const override; 2246 2247 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 2248 // FIXME: Assumes vectorcall is in use. 2249 return isX86VectorTypeForVectorCall(getContext(), Ty); 2250 } 2251 2252 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 2253 uint64_t NumMembers) const override { 2254 // FIXME: Assumes vectorcall is in use. 2255 return isX86VectorCallAggregateSmallEnough(NumMembers); 2256 } 2257 2258 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars, 2259 bool asReturnValue) const override { 2260 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2261 } 2262 2263 bool isSwiftErrorInRegister() const override { 2264 return true; 2265 } 2266 2267 private: 2268 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType, 2269 bool IsVectorCall, bool IsRegCall) const; 2270 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs, 2271 const ABIArgInfo ¤t) const; 2272 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs, 2273 bool IsVectorCall, bool IsRegCall) const; 2274 2275 X86AVXABILevel AVXLevel; 2276 2277 bool IsMingw64; 2278 }; 2279 2280 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2281 public: 2282 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2283 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {} 2284 2285 const X86_64ABIInfo &getABIInfo() const { 2286 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 2287 } 2288 2289 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks 2290 /// the autoreleaseRV/retainRV optimization. 2291 bool shouldSuppressTailCallsOfRetainAutoreleasedReturnValue() const override { 2292 return true; 2293 } 2294 2295 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2296 return 7; 2297 } 2298 2299 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2300 llvm::Value *Address) const override { 2301 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2302 2303 // 0-15 are the 16 integer registers. 2304 // 16 is %rip. 2305 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2306 return false; 2307 } 2308 2309 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 2310 StringRef Constraint, 2311 llvm::Type* Ty) const override { 2312 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 2313 } 2314 2315 bool isNoProtoCallVariadic(const CallArgList &args, 2316 const FunctionNoProtoType *fnType) const override { 2317 // The default CC on x86-64 sets %al to the number of SSA 2318 // registers used, and GCC sets this when calling an unprototyped 2319 // function, so we override the default behavior. However, don't do 2320 // that when AVX types are involved: the ABI explicitly states it is 2321 // undefined, and it doesn't work in practice because of how the ABI 2322 // defines varargs anyway. 2323 if (fnType->getCallConv() == CC_C) { 2324 bool HasAVXType = false; 2325 for (CallArgList::const_iterator 2326 it = args.begin(), ie = args.end(); it != ie; ++it) { 2327 if (getABIInfo().isPassedUsingAVXType(it->Ty)) { 2328 HasAVXType = true; 2329 break; 2330 } 2331 } 2332 2333 if (!HasAVXType) 2334 return true; 2335 } 2336 2337 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); 2338 } 2339 2340 llvm::Constant * 2341 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 2342 unsigned Sig = (0xeb << 0) | // jmp rel8 2343 (0x06 << 8) | // .+0x08 2344 ('v' << 16) | 2345 ('2' << 24); 2346 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 2347 } 2348 2349 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2350 CodeGen::CodeGenModule &CGM) const override { 2351 if (GV->isDeclaration()) 2352 return; 2353 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2354 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2355 llvm::Function *Fn = cast<llvm::Function>(GV); 2356 Fn->addFnAttr("stackrealign"); 2357 } 2358 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2359 llvm::Function *Fn = cast<llvm::Function>(GV); 2360 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2361 } 2362 } 2363 } 2364 }; 2365 2366 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) { 2367 // If the argument does not end in .lib, automatically add the suffix. 2368 // If the argument contains a space, enclose it in quotes. 2369 // This matches the behavior of MSVC. 2370 bool Quote = (Lib.find(" ") != StringRef::npos); 2371 std::string ArgStr = Quote ? "\"" : ""; 2372 ArgStr += Lib; 2373 if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a")) 2374 ArgStr += ".lib"; 2375 ArgStr += Quote ? "\"" : ""; 2376 return ArgStr; 2377 } 2378 2379 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo { 2380 public: 2381 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2382 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI, 2383 unsigned NumRegisterParameters) 2384 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI, 2385 Win32StructABI, NumRegisterParameters, false) {} 2386 2387 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2388 CodeGen::CodeGenModule &CGM) const override; 2389 2390 void getDependentLibraryOption(llvm::StringRef Lib, 2391 llvm::SmallString<24> &Opt) const override { 2392 Opt = "/DEFAULTLIB:"; 2393 Opt += qualifyWindowsLibrary(Lib); 2394 } 2395 2396 void getDetectMismatchOption(llvm::StringRef Name, 2397 llvm::StringRef Value, 2398 llvm::SmallString<32> &Opt) const override { 2399 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2400 } 2401 }; 2402 2403 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2404 CodeGen::CodeGenModule &CGM) { 2405 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) { 2406 2407 if (CGM.getCodeGenOpts().StackProbeSize != 4096) 2408 Fn->addFnAttr("stack-probe-size", 2409 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize)); 2410 if (CGM.getCodeGenOpts().NoStackArgProbe) 2411 Fn->addFnAttr("no-stack-arg-probe"); 2412 } 2413 } 2414 2415 void WinX86_32TargetCodeGenInfo::setTargetAttributes( 2416 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2417 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2418 if (GV->isDeclaration()) 2419 return; 2420 addStackProbeTargetAttributes(D, GV, CGM); 2421 } 2422 2423 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2424 public: 2425 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2426 X86AVXABILevel AVXLevel) 2427 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT, AVXLevel)) {} 2428 2429 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2430 CodeGen::CodeGenModule &CGM) const override; 2431 2432 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2433 return 7; 2434 } 2435 2436 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2437 llvm::Value *Address) const override { 2438 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2439 2440 // 0-15 are the 16 integer registers. 2441 // 16 is %rip. 2442 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2443 return false; 2444 } 2445 2446 void getDependentLibraryOption(llvm::StringRef Lib, 2447 llvm::SmallString<24> &Opt) const override { 2448 Opt = "/DEFAULTLIB:"; 2449 Opt += qualifyWindowsLibrary(Lib); 2450 } 2451 2452 void getDetectMismatchOption(llvm::StringRef Name, 2453 llvm::StringRef Value, 2454 llvm::SmallString<32> &Opt) const override { 2455 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2456 } 2457 }; 2458 2459 void WinX86_64TargetCodeGenInfo::setTargetAttributes( 2460 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2461 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2462 if (GV->isDeclaration()) 2463 return; 2464 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2465 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2466 llvm::Function *Fn = cast<llvm::Function>(GV); 2467 Fn->addFnAttr("stackrealign"); 2468 } 2469 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2470 llvm::Function *Fn = cast<llvm::Function>(GV); 2471 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2472 } 2473 } 2474 2475 addStackProbeTargetAttributes(D, GV, CGM); 2476 } 2477 } 2478 2479 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, 2480 Class &Hi) const { 2481 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: 2482 // 2483 // (a) If one of the classes is Memory, the whole argument is passed in 2484 // memory. 2485 // 2486 // (b) If X87UP is not preceded by X87, the whole argument is passed in 2487 // memory. 2488 // 2489 // (c) If the size of the aggregate exceeds two eightbytes and the first 2490 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole 2491 // argument is passed in memory. NOTE: This is necessary to keep the 2492 // ABI working for processors that don't support the __m256 type. 2493 // 2494 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. 2495 // 2496 // Some of these are enforced by the merging logic. Others can arise 2497 // only with unions; for example: 2498 // union { _Complex double; unsigned; } 2499 // 2500 // Note that clauses (b) and (c) were added in 0.98. 2501 // 2502 if (Hi == Memory) 2503 Lo = Memory; 2504 if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) 2505 Lo = Memory; 2506 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) 2507 Lo = Memory; 2508 if (Hi == SSEUp && Lo != SSE) 2509 Hi = SSE; 2510 } 2511 2512 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { 2513 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is 2514 // classified recursively so that always two fields are 2515 // considered. The resulting class is calculated according to 2516 // the classes of the fields in the eightbyte: 2517 // 2518 // (a) If both classes are equal, this is the resulting class. 2519 // 2520 // (b) If one of the classes is NO_CLASS, the resulting class is 2521 // the other class. 2522 // 2523 // (c) If one of the classes is MEMORY, the result is the MEMORY 2524 // class. 2525 // 2526 // (d) If one of the classes is INTEGER, the result is the 2527 // INTEGER. 2528 // 2529 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, 2530 // MEMORY is used as class. 2531 // 2532 // (f) Otherwise class SSE is used. 2533 2534 // Accum should never be memory (we should have returned) or 2535 // ComplexX87 (because this cannot be passed in a structure). 2536 assert((Accum != Memory && Accum != ComplexX87) && 2537 "Invalid accumulated classification during merge."); 2538 if (Accum == Field || Field == NoClass) 2539 return Accum; 2540 if (Field == Memory) 2541 return Memory; 2542 if (Accum == NoClass) 2543 return Field; 2544 if (Accum == Integer || Field == Integer) 2545 return Integer; 2546 if (Field == X87 || Field == X87Up || Field == ComplexX87 || 2547 Accum == X87 || Accum == X87Up) 2548 return Memory; 2549 return SSE; 2550 } 2551 2552 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, 2553 Class &Lo, Class &Hi, bool isNamedArg) const { 2554 // FIXME: This code can be simplified by introducing a simple value class for 2555 // Class pairs with appropriate constructor methods for the various 2556 // situations. 2557 2558 // FIXME: Some of the split computations are wrong; unaligned vectors 2559 // shouldn't be passed in registers for example, so there is no chance they 2560 // can straddle an eightbyte. Verify & simplify. 2561 2562 Lo = Hi = NoClass; 2563 2564 Class &Current = OffsetBase < 64 ? Lo : Hi; 2565 Current = Memory; 2566 2567 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 2568 BuiltinType::Kind k = BT->getKind(); 2569 2570 if (k == BuiltinType::Void) { 2571 Current = NoClass; 2572 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { 2573 Lo = Integer; 2574 Hi = Integer; 2575 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { 2576 Current = Integer; 2577 } else if (k == BuiltinType::Float || k == BuiltinType::Double) { 2578 Current = SSE; 2579 } else if (k == BuiltinType::LongDouble) { 2580 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2581 if (LDF == &llvm::APFloat::IEEEquad()) { 2582 Lo = SSE; 2583 Hi = SSEUp; 2584 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) { 2585 Lo = X87; 2586 Hi = X87Up; 2587 } else if (LDF == &llvm::APFloat::IEEEdouble()) { 2588 Current = SSE; 2589 } else 2590 llvm_unreachable("unexpected long double representation!"); 2591 } 2592 // FIXME: _Decimal32 and _Decimal64 are SSE. 2593 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). 2594 return; 2595 } 2596 2597 if (const EnumType *ET = Ty->getAs<EnumType>()) { 2598 // Classify the underlying integer type. 2599 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg); 2600 return; 2601 } 2602 2603 if (Ty->hasPointerRepresentation()) { 2604 Current = Integer; 2605 return; 2606 } 2607 2608 if (Ty->isMemberPointerType()) { 2609 if (Ty->isMemberFunctionPointerType()) { 2610 if (Has64BitPointers) { 2611 // If Has64BitPointers, this is an {i64, i64}, so classify both 2612 // Lo and Hi now. 2613 Lo = Hi = Integer; 2614 } else { 2615 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that 2616 // straddles an eightbyte boundary, Hi should be classified as well. 2617 uint64_t EB_FuncPtr = (OffsetBase) / 64; 2618 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64; 2619 if (EB_FuncPtr != EB_ThisAdj) { 2620 Lo = Hi = Integer; 2621 } else { 2622 Current = Integer; 2623 } 2624 } 2625 } else { 2626 Current = Integer; 2627 } 2628 return; 2629 } 2630 2631 if (const VectorType *VT = Ty->getAs<VectorType>()) { 2632 uint64_t Size = getContext().getTypeSize(VT); 2633 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) { 2634 // gcc passes the following as integer: 2635 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float> 2636 // 2 bytes - <2 x char>, <1 x short> 2637 // 1 byte - <1 x char> 2638 Current = Integer; 2639 2640 // If this type crosses an eightbyte boundary, it should be 2641 // split. 2642 uint64_t EB_Lo = (OffsetBase) / 64; 2643 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64; 2644 if (EB_Lo != EB_Hi) 2645 Hi = Lo; 2646 } else if (Size == 64) { 2647 QualType ElementType = VT->getElementType(); 2648 2649 // gcc passes <1 x double> in memory. :( 2650 if (ElementType->isSpecificBuiltinType(BuiltinType::Double)) 2651 return; 2652 2653 // gcc passes <1 x long long> as SSE but clang used to unconditionally 2654 // pass them as integer. For platforms where clang is the de facto 2655 // platform compiler, we must continue to use integer. 2656 if (!classifyIntegerMMXAsSSE() && 2657 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) || 2658 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) || 2659 ElementType->isSpecificBuiltinType(BuiltinType::Long) || 2660 ElementType->isSpecificBuiltinType(BuiltinType::ULong))) 2661 Current = Integer; 2662 else 2663 Current = SSE; 2664 2665 // If this type crosses an eightbyte boundary, it should be 2666 // split. 2667 if (OffsetBase && OffsetBase != 64) 2668 Hi = Lo; 2669 } else if (Size == 128 || 2670 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) { 2671 QualType ElementType = VT->getElementType(); 2672 2673 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :( 2674 if (passInt128VectorsInMem() && Size != 128 && 2675 (ElementType->isSpecificBuiltinType(BuiltinType::Int128) || 2676 ElementType->isSpecificBuiltinType(BuiltinType::UInt128))) 2677 return; 2678 2679 // Arguments of 256-bits are split into four eightbyte chunks. The 2680 // least significant one belongs to class SSE and all the others to class 2681 // SSEUP. The original Lo and Hi design considers that types can't be 2682 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. 2683 // This design isn't correct for 256-bits, but since there're no cases 2684 // where the upper parts would need to be inspected, avoid adding 2685 // complexity and just consider Hi to match the 64-256 part. 2686 // 2687 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in 2688 // registers if they are "named", i.e. not part of the "..." of a 2689 // variadic function. 2690 // 2691 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are 2692 // split into eight eightbyte chunks, one SSE and seven SSEUP. 2693 Lo = SSE; 2694 Hi = SSEUp; 2695 } 2696 return; 2697 } 2698 2699 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 2700 QualType ET = getContext().getCanonicalType(CT->getElementType()); 2701 2702 uint64_t Size = getContext().getTypeSize(Ty); 2703 if (ET->isIntegralOrEnumerationType()) { 2704 if (Size <= 64) 2705 Current = Integer; 2706 else if (Size <= 128) 2707 Lo = Hi = Integer; 2708 } else if (ET == getContext().FloatTy) { 2709 Current = SSE; 2710 } else if (ET == getContext().DoubleTy) { 2711 Lo = Hi = SSE; 2712 } else if (ET == getContext().LongDoubleTy) { 2713 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2714 if (LDF == &llvm::APFloat::IEEEquad()) 2715 Current = Memory; 2716 else if (LDF == &llvm::APFloat::x87DoubleExtended()) 2717 Current = ComplexX87; 2718 else if (LDF == &llvm::APFloat::IEEEdouble()) 2719 Lo = Hi = SSE; 2720 else 2721 llvm_unreachable("unexpected long double representation!"); 2722 } 2723 2724 // If this complex type crosses an eightbyte boundary then it 2725 // should be split. 2726 uint64_t EB_Real = (OffsetBase) / 64; 2727 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; 2728 if (Hi == NoClass && EB_Real != EB_Imag) 2729 Hi = Lo; 2730 2731 return; 2732 } 2733 2734 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 2735 // Arrays are treated like structures. 2736 2737 uint64_t Size = getContext().getTypeSize(Ty); 2738 2739 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 2740 // than eight eightbytes, ..., it has class MEMORY. 2741 if (Size > 512) 2742 return; 2743 2744 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned 2745 // fields, it has class MEMORY. 2746 // 2747 // Only need to check alignment of array base. 2748 if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) 2749 return; 2750 2751 // Otherwise implement simplified merge. We could be smarter about 2752 // this, but it isn't worth it and would be harder to verify. 2753 Current = NoClass; 2754 uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); 2755 uint64_t ArraySize = AT->getSize().getZExtValue(); 2756 2757 // The only case a 256-bit wide vector could be used is when the array 2758 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 2759 // to work for sizes wider than 128, early check and fallback to memory. 2760 // 2761 if (Size > 128 && 2762 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel))) 2763 return; 2764 2765 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { 2766 Class FieldLo, FieldHi; 2767 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg); 2768 Lo = merge(Lo, FieldLo); 2769 Hi = merge(Hi, FieldHi); 2770 if (Lo == Memory || Hi == Memory) 2771 break; 2772 } 2773 2774 postMerge(Size, Lo, Hi); 2775 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); 2776 return; 2777 } 2778 2779 if (const RecordType *RT = Ty->getAs<RecordType>()) { 2780 uint64_t Size = getContext().getTypeSize(Ty); 2781 2782 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 2783 // than eight eightbytes, ..., it has class MEMORY. 2784 if (Size > 512) 2785 return; 2786 2787 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial 2788 // copy constructor or a non-trivial destructor, it is passed by invisible 2789 // reference. 2790 if (getRecordArgABI(RT, getCXXABI())) 2791 return; 2792 2793 const RecordDecl *RD = RT->getDecl(); 2794 2795 // Assume variable sized types are passed in memory. 2796 if (RD->hasFlexibleArrayMember()) 2797 return; 2798 2799 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 2800 2801 // Reset Lo class, this will be recomputed. 2802 Current = NoClass; 2803 2804 // If this is a C++ record, classify the bases first. 2805 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 2806 for (const auto &I : CXXRD->bases()) { 2807 assert(!I.isVirtual() && !I.getType()->isDependentType() && 2808 "Unexpected base class!"); 2809 const auto *Base = 2810 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 2811 2812 // Classify this field. 2813 // 2814 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a 2815 // single eightbyte, each is classified separately. Each eightbyte gets 2816 // initialized to class NO_CLASS. 2817 Class FieldLo, FieldHi; 2818 uint64_t Offset = 2819 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base)); 2820 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg); 2821 Lo = merge(Lo, FieldLo); 2822 Hi = merge(Hi, FieldHi); 2823 if (Lo == Memory || Hi == Memory) { 2824 postMerge(Size, Lo, Hi); 2825 return; 2826 } 2827 } 2828 } 2829 2830 // Classify the fields one at a time, merging the results. 2831 unsigned idx = 0; 2832 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 2833 i != e; ++i, ++idx) { 2834 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 2835 bool BitField = i->isBitField(); 2836 2837 // Ignore padding bit-fields. 2838 if (BitField && i->isUnnamedBitfield()) 2839 continue; 2840 2841 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than 2842 // four eightbytes, or it contains unaligned fields, it has class MEMORY. 2843 // 2844 // The only case a 256-bit wide vector could be used is when the struct 2845 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 2846 // to work for sizes wider than 128, early check and fallback to memory. 2847 // 2848 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) || 2849 Size > getNativeVectorSizeForAVXABI(AVXLevel))) { 2850 Lo = Memory; 2851 postMerge(Size, Lo, Hi); 2852 return; 2853 } 2854 // Note, skip this test for bit-fields, see below. 2855 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { 2856 Lo = Memory; 2857 postMerge(Size, Lo, Hi); 2858 return; 2859 } 2860 2861 // Classify this field. 2862 // 2863 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate 2864 // exceeds a single eightbyte, each is classified 2865 // separately. Each eightbyte gets initialized to class 2866 // NO_CLASS. 2867 Class FieldLo, FieldHi; 2868 2869 // Bit-fields require special handling, they do not force the 2870 // structure to be passed in memory even if unaligned, and 2871 // therefore they can straddle an eightbyte. 2872 if (BitField) { 2873 assert(!i->isUnnamedBitfield()); 2874 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 2875 uint64_t Size = i->getBitWidthValue(getContext()); 2876 2877 uint64_t EB_Lo = Offset / 64; 2878 uint64_t EB_Hi = (Offset + Size - 1) / 64; 2879 2880 if (EB_Lo) { 2881 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); 2882 FieldLo = NoClass; 2883 FieldHi = Integer; 2884 } else { 2885 FieldLo = Integer; 2886 FieldHi = EB_Hi ? Integer : NoClass; 2887 } 2888 } else 2889 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); 2890 Lo = merge(Lo, FieldLo); 2891 Hi = merge(Hi, FieldHi); 2892 if (Lo == Memory || Hi == Memory) 2893 break; 2894 } 2895 2896 postMerge(Size, Lo, Hi); 2897 } 2898 } 2899 2900 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { 2901 // If this is a scalar LLVM value then assume LLVM will pass it in the right 2902 // place naturally. 2903 if (!isAggregateTypeForABI(Ty)) { 2904 // Treat an enum type as its underlying type. 2905 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2906 Ty = EnumTy->getDecl()->getIntegerType(); 2907 2908 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 2909 : ABIArgInfo::getDirect()); 2910 } 2911 2912 return getNaturalAlignIndirect(Ty); 2913 } 2914 2915 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { 2916 if (const VectorType *VecTy = Ty->getAs<VectorType>()) { 2917 uint64_t Size = getContext().getTypeSize(VecTy); 2918 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel); 2919 if (Size <= 64 || Size > LargestVector) 2920 return true; 2921 QualType EltTy = VecTy->getElementType(); 2922 if (passInt128VectorsInMem() && 2923 (EltTy->isSpecificBuiltinType(BuiltinType::Int128) || 2924 EltTy->isSpecificBuiltinType(BuiltinType::UInt128))) 2925 return true; 2926 } 2927 2928 return false; 2929 } 2930 2931 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty, 2932 unsigned freeIntRegs) const { 2933 // If this is a scalar LLVM value then assume LLVM will pass it in the right 2934 // place naturally. 2935 // 2936 // This assumption is optimistic, as there could be free registers available 2937 // when we need to pass this argument in memory, and LLVM could try to pass 2938 // the argument in the free register. This does not seem to happen currently, 2939 // but this code would be much safer if we could mark the argument with 2940 // 'onstack'. See PR12193. 2941 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) { 2942 // Treat an enum type as its underlying type. 2943 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2944 Ty = EnumTy->getDecl()->getIntegerType(); 2945 2946 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 2947 : ABIArgInfo::getDirect()); 2948 } 2949 2950 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 2951 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 2952 2953 // Compute the byval alignment. We specify the alignment of the byval in all 2954 // cases so that the mid-level optimizer knows the alignment of the byval. 2955 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); 2956 2957 // Attempt to avoid passing indirect results using byval when possible. This 2958 // is important for good codegen. 2959 // 2960 // We do this by coercing the value into a scalar type which the backend can 2961 // handle naturally (i.e., without using byval). 2962 // 2963 // For simplicity, we currently only do this when we have exhausted all of the 2964 // free integer registers. Doing this when there are free integer registers 2965 // would require more care, as we would have to ensure that the coerced value 2966 // did not claim the unused register. That would require either reording the 2967 // arguments to the function (so that any subsequent inreg values came first), 2968 // or only doing this optimization when there were no following arguments that 2969 // might be inreg. 2970 // 2971 // We currently expect it to be rare (particularly in well written code) for 2972 // arguments to be passed on the stack when there are still free integer 2973 // registers available (this would typically imply large structs being passed 2974 // by value), so this seems like a fair tradeoff for now. 2975 // 2976 // We can revisit this if the backend grows support for 'onstack' parameter 2977 // attributes. See PR12193. 2978 if (freeIntRegs == 0) { 2979 uint64_t Size = getContext().getTypeSize(Ty); 2980 2981 // If this type fits in an eightbyte, coerce it into the matching integral 2982 // type, which will end up on the stack (with alignment 8). 2983 if (Align == 8 && Size <= 64) 2984 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 2985 Size)); 2986 } 2987 2988 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align)); 2989 } 2990 2991 /// The ABI specifies that a value should be passed in a full vector XMM/YMM 2992 /// register. Pick an LLVM IR type that will be passed as a vector register. 2993 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { 2994 // Wrapper structs/arrays that only contain vectors are passed just like 2995 // vectors; strip them off if present. 2996 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext())) 2997 Ty = QualType(InnerTy, 0); 2998 2999 llvm::Type *IRType = CGT.ConvertType(Ty); 3000 if (isa<llvm::VectorType>(IRType)) { 3001 // Don't pass vXi128 vectors in their native type, the backend can't 3002 // legalize them. 3003 if (passInt128VectorsInMem() && 3004 IRType->getVectorElementType()->isIntegerTy(128)) { 3005 // Use a vXi64 vector. 3006 uint64_t Size = getContext().getTypeSize(Ty); 3007 return llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()), 3008 Size / 64); 3009 } 3010 3011 return IRType; 3012 } 3013 3014 if (IRType->getTypeID() == llvm::Type::FP128TyID) 3015 return IRType; 3016 3017 // We couldn't find the preferred IR vector type for 'Ty'. 3018 uint64_t Size = getContext().getTypeSize(Ty); 3019 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!"); 3020 3021 3022 // Return a LLVM IR vector type based on the size of 'Ty'. 3023 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 3024 Size / 64); 3025 } 3026 3027 /// BitsContainNoUserData - Return true if the specified [start,end) bit range 3028 /// is known to either be off the end of the specified type or being in 3029 /// alignment padding. The user type specified is known to be at most 128 bits 3030 /// in size, and have passed through X86_64ABIInfo::classify with a successful 3031 /// classification that put one of the two halves in the INTEGER class. 3032 /// 3033 /// It is conservatively correct to return false. 3034 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, 3035 unsigned EndBit, ASTContext &Context) { 3036 // If the bytes being queried are off the end of the type, there is no user 3037 // data hiding here. This handles analysis of builtins, vectors and other 3038 // types that don't contain interesting padding. 3039 unsigned TySize = (unsigned)Context.getTypeSize(Ty); 3040 if (TySize <= StartBit) 3041 return true; 3042 3043 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 3044 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); 3045 unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); 3046 3047 // Check each element to see if the element overlaps with the queried range. 3048 for (unsigned i = 0; i != NumElts; ++i) { 3049 // If the element is after the span we care about, then we're done.. 3050 unsigned EltOffset = i*EltSize; 3051 if (EltOffset >= EndBit) break; 3052 3053 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; 3054 if (!BitsContainNoUserData(AT->getElementType(), EltStart, 3055 EndBit-EltOffset, Context)) 3056 return false; 3057 } 3058 // If it overlaps no elements, then it is safe to process as padding. 3059 return true; 3060 } 3061 3062 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3063 const RecordDecl *RD = RT->getDecl(); 3064 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 3065 3066 // If this is a C++ record, check the bases first. 3067 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3068 for (const auto &I : CXXRD->bases()) { 3069 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3070 "Unexpected base class!"); 3071 const auto *Base = 3072 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3073 3074 // If the base is after the span we care about, ignore it. 3075 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base)); 3076 if (BaseOffset >= EndBit) continue; 3077 3078 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; 3079 if (!BitsContainNoUserData(I.getType(), BaseStart, 3080 EndBit-BaseOffset, Context)) 3081 return false; 3082 } 3083 } 3084 3085 // Verify that no field has data that overlaps the region of interest. Yes 3086 // this could be sped up a lot by being smarter about queried fields, 3087 // however we're only looking at structs up to 16 bytes, so we don't care 3088 // much. 3089 unsigned idx = 0; 3090 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3091 i != e; ++i, ++idx) { 3092 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); 3093 3094 // If we found a field after the region we care about, then we're done. 3095 if (FieldOffset >= EndBit) break; 3096 3097 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; 3098 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, 3099 Context)) 3100 return false; 3101 } 3102 3103 // If nothing in this record overlapped the area of interest, then we're 3104 // clean. 3105 return true; 3106 } 3107 3108 return false; 3109 } 3110 3111 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a 3112 /// float member at the specified offset. For example, {int,{float}} has a 3113 /// float at offset 4. It is conservatively correct for this routine to return 3114 /// false. 3115 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset, 3116 const llvm::DataLayout &TD) { 3117 // Base case if we find a float. 3118 if (IROffset == 0 && IRType->isFloatTy()) 3119 return true; 3120 3121 // If this is a struct, recurse into the field at the specified offset. 3122 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3123 const llvm::StructLayout *SL = TD.getStructLayout(STy); 3124 unsigned Elt = SL->getElementContainingOffset(IROffset); 3125 IROffset -= SL->getElementOffset(Elt); 3126 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD); 3127 } 3128 3129 // If this is an array, recurse into the field at the specified offset. 3130 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3131 llvm::Type *EltTy = ATy->getElementType(); 3132 unsigned EltSize = TD.getTypeAllocSize(EltTy); 3133 IROffset -= IROffset/EltSize*EltSize; 3134 return ContainsFloatAtOffset(EltTy, IROffset, TD); 3135 } 3136 3137 return false; 3138 } 3139 3140 3141 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the 3142 /// low 8 bytes of an XMM register, corresponding to the SSE class. 3143 llvm::Type *X86_64ABIInfo:: 3144 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3145 QualType SourceTy, unsigned SourceOffset) const { 3146 // The only three choices we have are either double, <2 x float>, or float. We 3147 // pass as float if the last 4 bytes is just padding. This happens for 3148 // structs that contain 3 floats. 3149 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32, 3150 SourceOffset*8+64, getContext())) 3151 return llvm::Type::getFloatTy(getVMContext()); 3152 3153 // We want to pass as <2 x float> if the LLVM IR type contains a float at 3154 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the 3155 // case. 3156 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) && 3157 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout())) 3158 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2); 3159 3160 return llvm::Type::getDoubleTy(getVMContext()); 3161 } 3162 3163 3164 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in 3165 /// an 8-byte GPR. This means that we either have a scalar or we are talking 3166 /// about the high or low part of an up-to-16-byte struct. This routine picks 3167 /// the best LLVM IR type to represent this, which may be i64 or may be anything 3168 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, 3169 /// etc). 3170 /// 3171 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for 3172 /// the source type. IROffset is an offset in bytes into the LLVM IR type that 3173 /// the 8-byte value references. PrefType may be null. 3174 /// 3175 /// SourceTy is the source-level type for the entire argument. SourceOffset is 3176 /// an offset into this that we're processing (which is always either 0 or 8). 3177 /// 3178 llvm::Type *X86_64ABIInfo:: 3179 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3180 QualType SourceTy, unsigned SourceOffset) const { 3181 // If we're dealing with an un-offset LLVM IR type, then it means that we're 3182 // returning an 8-byte unit starting with it. See if we can safely use it. 3183 if (IROffset == 0) { 3184 // Pointers and int64's always fill the 8-byte unit. 3185 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) || 3186 IRType->isIntegerTy(64)) 3187 return IRType; 3188 3189 // If we have a 1/2/4-byte integer, we can use it only if the rest of the 3190 // goodness in the source type is just tail padding. This is allowed to 3191 // kick in for struct {double,int} on the int, but not on 3192 // struct{double,int,int} because we wouldn't return the second int. We 3193 // have to do this analysis on the source type because we can't depend on 3194 // unions being lowered a specific way etc. 3195 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || 3196 IRType->isIntegerTy(32) || 3197 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) { 3198 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 : 3199 cast<llvm::IntegerType>(IRType)->getBitWidth(); 3200 3201 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, 3202 SourceOffset*8+64, getContext())) 3203 return IRType; 3204 } 3205 } 3206 3207 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3208 // If this is a struct, recurse into the field at the specified offset. 3209 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy); 3210 if (IROffset < SL->getSizeInBytes()) { 3211 unsigned FieldIdx = SL->getElementContainingOffset(IROffset); 3212 IROffset -= SL->getElementOffset(FieldIdx); 3213 3214 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, 3215 SourceTy, SourceOffset); 3216 } 3217 } 3218 3219 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3220 llvm::Type *EltTy = ATy->getElementType(); 3221 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy); 3222 unsigned EltOffset = IROffset/EltSize*EltSize; 3223 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, 3224 SourceOffset); 3225 } 3226 3227 // Okay, we don't have any better idea of what to pass, so we pass this in an 3228 // integer register that isn't too big to fit the rest of the struct. 3229 unsigned TySizeInBytes = 3230 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); 3231 3232 assert(TySizeInBytes != SourceOffset && "Empty field?"); 3233 3234 // It is always safe to classify this as an integer type up to i64 that 3235 // isn't larger than the structure. 3236 return llvm::IntegerType::get(getVMContext(), 3237 std::min(TySizeInBytes-SourceOffset, 8U)*8); 3238 } 3239 3240 3241 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally 3242 /// be used as elements of a two register pair to pass or return, return a 3243 /// first class aggregate to represent them. For example, if the low part of 3244 /// a by-value argument should be passed as i32* and the high part as float, 3245 /// return {i32*, float}. 3246 static llvm::Type * 3247 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, 3248 const llvm::DataLayout &TD) { 3249 // In order to correctly satisfy the ABI, we need to the high part to start 3250 // at offset 8. If the high and low parts we inferred are both 4-byte types 3251 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have 3252 // the second element at offset 8. Check for this: 3253 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); 3254 unsigned HiAlign = TD.getABITypeAlignment(Hi); 3255 unsigned HiStart = llvm::alignTo(LoSize, HiAlign); 3256 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!"); 3257 3258 // To handle this, we have to increase the size of the low part so that the 3259 // second element will start at an 8 byte offset. We can't increase the size 3260 // of the second element because it might make us access off the end of the 3261 // struct. 3262 if (HiStart != 8) { 3263 // There are usually two sorts of types the ABI generation code can produce 3264 // for the low part of a pair that aren't 8 bytes in size: float or 3265 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and 3266 // NaCl). 3267 // Promote these to a larger type. 3268 if (Lo->isFloatTy()) 3269 Lo = llvm::Type::getDoubleTy(Lo->getContext()); 3270 else { 3271 assert((Lo->isIntegerTy() || Lo->isPointerTy()) 3272 && "Invalid/unknown lo type"); 3273 Lo = llvm::Type::getInt64Ty(Lo->getContext()); 3274 } 3275 } 3276 3277 llvm::StructType *Result = llvm::StructType::get(Lo, Hi); 3278 3279 // Verify that the second element is at an 8-byte offset. 3280 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && 3281 "Invalid x86-64 argument pair!"); 3282 return Result; 3283 } 3284 3285 ABIArgInfo X86_64ABIInfo:: 3286 classifyReturnType(QualType RetTy) const { 3287 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the 3288 // classification algorithm. 3289 X86_64ABIInfo::Class Lo, Hi; 3290 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true); 3291 3292 // Check some invariants. 3293 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3294 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3295 3296 llvm::Type *ResType = nullptr; 3297 switch (Lo) { 3298 case NoClass: 3299 if (Hi == NoClass) 3300 return ABIArgInfo::getIgnore(); 3301 // If the low part is just padding, it takes no register, leave ResType 3302 // null. 3303 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3304 "Unknown missing lo part"); 3305 break; 3306 3307 case SSEUp: 3308 case X87Up: 3309 llvm_unreachable("Invalid classification for lo word."); 3310 3311 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via 3312 // hidden argument. 3313 case Memory: 3314 return getIndirectReturnResult(RetTy); 3315 3316 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next 3317 // available register of the sequence %rax, %rdx is used. 3318 case Integer: 3319 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3320 3321 // If we have a sign or zero extended integer, make sure to return Extend 3322 // so that the parameter gets the right LLVM IR attributes. 3323 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3324 // Treat an enum type as its underlying type. 3325 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3326 RetTy = EnumTy->getDecl()->getIntegerType(); 3327 3328 if (RetTy->isIntegralOrEnumerationType() && 3329 RetTy->isPromotableIntegerType()) 3330 return ABIArgInfo::getExtend(RetTy); 3331 } 3332 break; 3333 3334 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next 3335 // available SSE register of the sequence %xmm0, %xmm1 is used. 3336 case SSE: 3337 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3338 break; 3339 3340 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is 3341 // returned on the X87 stack in %st0 as 80-bit x87 number. 3342 case X87: 3343 ResType = llvm::Type::getX86_FP80Ty(getVMContext()); 3344 break; 3345 3346 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real 3347 // part of the value is returned in %st0 and the imaginary part in 3348 // %st1. 3349 case ComplexX87: 3350 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); 3351 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), 3352 llvm::Type::getX86_FP80Ty(getVMContext())); 3353 break; 3354 } 3355 3356 llvm::Type *HighPart = nullptr; 3357 switch (Hi) { 3358 // Memory was handled previously and X87 should 3359 // never occur as a hi class. 3360 case Memory: 3361 case X87: 3362 llvm_unreachable("Invalid classification for hi word."); 3363 3364 case ComplexX87: // Previously handled. 3365 case NoClass: 3366 break; 3367 3368 case Integer: 3369 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3370 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3371 return ABIArgInfo::getDirect(HighPart, 8); 3372 break; 3373 case SSE: 3374 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3375 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3376 return ABIArgInfo::getDirect(HighPart, 8); 3377 break; 3378 3379 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte 3380 // is passed in the next available eightbyte chunk if the last used 3381 // vector register. 3382 // 3383 // SSEUP should always be preceded by SSE, just widen. 3384 case SSEUp: 3385 assert(Lo == SSE && "Unexpected SSEUp classification."); 3386 ResType = GetByteVectorType(RetTy); 3387 break; 3388 3389 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is 3390 // returned together with the previous X87 value in %st0. 3391 case X87Up: 3392 // If X87Up is preceded by X87, we don't need to do 3393 // anything. However, in some cases with unions it may not be 3394 // preceded by X87. In such situations we follow gcc and pass the 3395 // extra bits in an SSE reg. 3396 if (Lo != X87) { 3397 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3398 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3399 return ABIArgInfo::getDirect(HighPart, 8); 3400 } 3401 break; 3402 } 3403 3404 // If a high part was specified, merge it together with the low part. It is 3405 // known to pass in the high eightbyte of the result. We do this by forming a 3406 // first class struct aggregate with the high and low part: {low, high} 3407 if (HighPart) 3408 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3409 3410 return ABIArgInfo::getDirect(ResType); 3411 } 3412 3413 ABIArgInfo X86_64ABIInfo::classifyArgumentType( 3414 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE, 3415 bool isNamedArg) 3416 const 3417 { 3418 Ty = useFirstFieldIfTransparentUnion(Ty); 3419 3420 X86_64ABIInfo::Class Lo, Hi; 3421 classify(Ty, 0, Lo, Hi, isNamedArg); 3422 3423 // Check some invariants. 3424 // FIXME: Enforce these by construction. 3425 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3426 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3427 3428 neededInt = 0; 3429 neededSSE = 0; 3430 llvm::Type *ResType = nullptr; 3431 switch (Lo) { 3432 case NoClass: 3433 if (Hi == NoClass) 3434 return ABIArgInfo::getIgnore(); 3435 // If the low part is just padding, it takes no register, leave ResType 3436 // null. 3437 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3438 "Unknown missing lo part"); 3439 break; 3440 3441 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument 3442 // on the stack. 3443 case Memory: 3444 3445 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or 3446 // COMPLEX_X87, it is passed in memory. 3447 case X87: 3448 case ComplexX87: 3449 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect) 3450 ++neededInt; 3451 return getIndirectResult(Ty, freeIntRegs); 3452 3453 case SSEUp: 3454 case X87Up: 3455 llvm_unreachable("Invalid classification for lo word."); 3456 3457 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next 3458 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 3459 // and %r9 is used. 3460 case Integer: 3461 ++neededInt; 3462 3463 // Pick an 8-byte type based on the preferred type. 3464 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); 3465 3466 // If we have a sign or zero extended integer, make sure to return Extend 3467 // so that the parameter gets the right LLVM IR attributes. 3468 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3469 // Treat an enum type as its underlying type. 3470 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3471 Ty = EnumTy->getDecl()->getIntegerType(); 3472 3473 if (Ty->isIntegralOrEnumerationType() && 3474 Ty->isPromotableIntegerType()) 3475 return ABIArgInfo::getExtend(Ty); 3476 } 3477 3478 break; 3479 3480 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next 3481 // available SSE register is used, the registers are taken in the 3482 // order from %xmm0 to %xmm7. 3483 case SSE: { 3484 llvm::Type *IRType = CGT.ConvertType(Ty); 3485 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); 3486 ++neededSSE; 3487 break; 3488 } 3489 } 3490 3491 llvm::Type *HighPart = nullptr; 3492 switch (Hi) { 3493 // Memory was handled previously, ComplexX87 and X87 should 3494 // never occur as hi classes, and X87Up must be preceded by X87, 3495 // which is passed in memory. 3496 case Memory: 3497 case X87: 3498 case ComplexX87: 3499 llvm_unreachable("Invalid classification for hi word."); 3500 3501 case NoClass: break; 3502 3503 case Integer: 3504 ++neededInt; 3505 // Pick an 8-byte type based on the preferred type. 3506 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3507 3508 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3509 return ABIArgInfo::getDirect(HighPart, 8); 3510 break; 3511 3512 // X87Up generally doesn't occur here (long double is passed in 3513 // memory), except in situations involving unions. 3514 case X87Up: 3515 case SSE: 3516 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3517 3518 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3519 return ABIArgInfo::getDirect(HighPart, 8); 3520 3521 ++neededSSE; 3522 break; 3523 3524 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the 3525 // eightbyte is passed in the upper half of the last used SSE 3526 // register. This only happens when 128-bit vectors are passed. 3527 case SSEUp: 3528 assert(Lo == SSE && "Unexpected SSEUp classification"); 3529 ResType = GetByteVectorType(Ty); 3530 break; 3531 } 3532 3533 // If a high part was specified, merge it together with the low part. It is 3534 // known to pass in the high eightbyte of the result. We do this by forming a 3535 // first class struct aggregate with the high and low part: {low, high} 3536 if (HighPart) 3537 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3538 3539 return ABIArgInfo::getDirect(ResType); 3540 } 3541 3542 ABIArgInfo 3543 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 3544 unsigned &NeededSSE) const { 3545 auto RT = Ty->getAs<RecordType>(); 3546 assert(RT && "classifyRegCallStructType only valid with struct types"); 3547 3548 if (RT->getDecl()->hasFlexibleArrayMember()) 3549 return getIndirectReturnResult(Ty); 3550 3551 // Sum up bases 3552 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 3553 if (CXXRD->isDynamicClass()) { 3554 NeededInt = NeededSSE = 0; 3555 return getIndirectReturnResult(Ty); 3556 } 3557 3558 for (const auto &I : CXXRD->bases()) 3559 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE) 3560 .isIndirect()) { 3561 NeededInt = NeededSSE = 0; 3562 return getIndirectReturnResult(Ty); 3563 } 3564 } 3565 3566 // Sum up members 3567 for (const auto *FD : RT->getDecl()->fields()) { 3568 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) { 3569 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE) 3570 .isIndirect()) { 3571 NeededInt = NeededSSE = 0; 3572 return getIndirectReturnResult(Ty); 3573 } 3574 } else { 3575 unsigned LocalNeededInt, LocalNeededSSE; 3576 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt, 3577 LocalNeededSSE, true) 3578 .isIndirect()) { 3579 NeededInt = NeededSSE = 0; 3580 return getIndirectReturnResult(Ty); 3581 } 3582 NeededInt += LocalNeededInt; 3583 NeededSSE += LocalNeededSSE; 3584 } 3585 } 3586 3587 return ABIArgInfo::getDirect(); 3588 } 3589 3590 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty, 3591 unsigned &NeededInt, 3592 unsigned &NeededSSE) const { 3593 3594 NeededInt = 0; 3595 NeededSSE = 0; 3596 3597 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE); 3598 } 3599 3600 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 3601 3602 const unsigned CallingConv = FI.getCallingConvention(); 3603 // It is possible to force Win64 calling convention on any x86_64 target by 3604 // using __attribute__((ms_abi)). In such case to correctly emit Win64 3605 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo. 3606 if (CallingConv == llvm::CallingConv::Win64) { 3607 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel); 3608 Win64ABIInfo.computeInfo(FI); 3609 return; 3610 } 3611 3612 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall; 3613 3614 // Keep track of the number of assigned registers. 3615 unsigned FreeIntRegs = IsRegCall ? 11 : 6; 3616 unsigned FreeSSERegs = IsRegCall ? 16 : 8; 3617 unsigned NeededInt, NeededSSE; 3618 3619 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 3620 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() && 3621 !FI.getReturnType()->getTypePtr()->isUnionType()) { 3622 FI.getReturnInfo() = 3623 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE); 3624 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3625 FreeIntRegs -= NeededInt; 3626 FreeSSERegs -= NeededSSE; 3627 } else { 3628 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3629 } 3630 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) { 3631 // Complex Long Double Type is passed in Memory when Regcall 3632 // calling convention is used. 3633 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>(); 3634 if (getContext().getCanonicalType(CT->getElementType()) == 3635 getContext().LongDoubleTy) 3636 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3637 } else 3638 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 3639 } 3640 3641 // If the return value is indirect, then the hidden argument is consuming one 3642 // integer register. 3643 if (FI.getReturnInfo().isIndirect()) 3644 --FreeIntRegs; 3645 3646 // The chain argument effectively gives us another free register. 3647 if (FI.isChainCall()) 3648 ++FreeIntRegs; 3649 3650 unsigned NumRequiredArgs = FI.getNumRequiredArgs(); 3651 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers 3652 // get assigned (in left-to-right order) for passing as follows... 3653 unsigned ArgNo = 0; 3654 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3655 it != ie; ++it, ++ArgNo) { 3656 bool IsNamedArg = ArgNo < NumRequiredArgs; 3657 3658 if (IsRegCall && it->type->isStructureOrClassType()) 3659 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE); 3660 else 3661 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt, 3662 NeededSSE, IsNamedArg); 3663 3664 // AMD64-ABI 3.2.3p3: If there are no registers available for any 3665 // eightbyte of an argument, the whole argument is passed on the 3666 // stack. If registers have already been assigned for some 3667 // eightbytes of such an argument, the assignments get reverted. 3668 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3669 FreeIntRegs -= NeededInt; 3670 FreeSSERegs -= NeededSSE; 3671 } else { 3672 it->info = getIndirectResult(it->type, FreeIntRegs); 3673 } 3674 } 3675 } 3676 3677 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF, 3678 Address VAListAddr, QualType Ty) { 3679 Address overflow_arg_area_p = 3680 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); 3681 llvm::Value *overflow_arg_area = 3682 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); 3683 3684 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 3685 // byte boundary if alignment needed by type exceeds 8 byte boundary. 3686 // It isn't stated explicitly in the standard, but in practice we use 3687 // alignment greater than 16 where necessary. 3688 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 3689 if (Align > CharUnits::fromQuantity(8)) { 3690 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area, 3691 Align); 3692 } 3693 3694 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. 3695 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 3696 llvm::Value *Res = 3697 CGF.Builder.CreateBitCast(overflow_arg_area, 3698 llvm::PointerType::getUnqual(LTy)); 3699 3700 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: 3701 // l->overflow_arg_area + sizeof(type). 3702 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to 3703 // an 8 byte boundary. 3704 3705 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; 3706 llvm::Value *Offset = 3707 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); 3708 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset, 3709 "overflow_arg_area.next"); 3710 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); 3711 3712 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. 3713 return Address(Res, Align); 3714 } 3715 3716 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 3717 QualType Ty) const { 3718 // Assume that va_list type is correct; should be pointer to LLVM type: 3719 // struct { 3720 // i32 gp_offset; 3721 // i32 fp_offset; 3722 // i8* overflow_arg_area; 3723 // i8* reg_save_area; 3724 // }; 3725 unsigned neededInt, neededSSE; 3726 3727 Ty = getContext().getCanonicalType(Ty); 3728 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE, 3729 /*isNamedArg*/false); 3730 3731 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed 3732 // in the registers. If not go to step 7. 3733 if (!neededInt && !neededSSE) 3734 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 3735 3736 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of 3737 // general purpose registers needed to pass type and num_fp to hold 3738 // the number of floating point registers needed. 3739 3740 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into 3741 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or 3742 // l->fp_offset > 304 - num_fp * 16 go to step 7. 3743 // 3744 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of 3745 // register save space). 3746 3747 llvm::Value *InRegs = nullptr; 3748 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid(); 3749 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr; 3750 if (neededInt) { 3751 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); 3752 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); 3753 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); 3754 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); 3755 } 3756 3757 if (neededSSE) { 3758 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); 3759 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); 3760 llvm::Value *FitsInFP = 3761 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); 3762 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); 3763 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; 3764 } 3765 3766 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 3767 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 3768 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 3769 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 3770 3771 // Emit code to load the value if it was passed in registers. 3772 3773 CGF.EmitBlock(InRegBlock); 3774 3775 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with 3776 // an offset of l->gp_offset and/or l->fp_offset. This may require 3777 // copying to a temporary location in case the parameter is passed 3778 // in different register classes or requires an alignment greater 3779 // than 8 for general purpose registers and 16 for XMM registers. 3780 // 3781 // FIXME: This really results in shameful code when we end up needing to 3782 // collect arguments from different places; often what should result in a 3783 // simple assembling of a structure from scattered addresses has many more 3784 // loads than necessary. Can we clean this up? 3785 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 3786 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad( 3787 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area"); 3788 3789 Address RegAddr = Address::invalid(); 3790 if (neededInt && neededSSE) { 3791 // FIXME: Cleanup. 3792 assert(AI.isDirect() && "Unexpected ABI info for mixed regs"); 3793 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); 3794 Address Tmp = CGF.CreateMemTemp(Ty); 3795 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 3796 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); 3797 llvm::Type *TyLo = ST->getElementType(0); 3798 llvm::Type *TyHi = ST->getElementType(1); 3799 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && 3800 "Unexpected ABI info for mixed regs"); 3801 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); 3802 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); 3803 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset); 3804 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset); 3805 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr; 3806 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr; 3807 3808 // Copy the first element. 3809 // FIXME: Our choice of alignment here and below is probably pessimistic. 3810 llvm::Value *V = CGF.Builder.CreateAlignedLoad( 3811 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo), 3812 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo))); 3813 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 3814 3815 // Copy the second element. 3816 V = CGF.Builder.CreateAlignedLoad( 3817 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi), 3818 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi))); 3819 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 3820 3821 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 3822 } else if (neededInt) { 3823 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset), 3824 CharUnits::fromQuantity(8)); 3825 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 3826 3827 // Copy to a temporary if necessary to ensure the appropriate alignment. 3828 std::pair<CharUnits, CharUnits> SizeAlign = 3829 getContext().getTypeInfoInChars(Ty); 3830 uint64_t TySize = SizeAlign.first.getQuantity(); 3831 CharUnits TyAlign = SizeAlign.second; 3832 3833 // Copy into a temporary if the type is more aligned than the 3834 // register save area. 3835 if (TyAlign.getQuantity() > 8) { 3836 Address Tmp = CGF.CreateMemTemp(Ty); 3837 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false); 3838 RegAddr = Tmp; 3839 } 3840 3841 } else if (neededSSE == 1) { 3842 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), 3843 CharUnits::fromQuantity(16)); 3844 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 3845 } else { 3846 assert(neededSSE == 2 && "Invalid number of needed registers!"); 3847 // SSE registers are spaced 16 bytes apart in the register save 3848 // area, we need to collect the two eightbytes together. 3849 // The ABI isn't explicit about this, but it seems reasonable 3850 // to assume that the slots are 16-byte aligned, since the stack is 3851 // naturally 16-byte aligned and the prologue is expected to store 3852 // all the SSE registers to the RSA. 3853 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), 3854 CharUnits::fromQuantity(16)); 3855 Address RegAddrHi = 3856 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo, 3857 CharUnits::fromQuantity(16)); 3858 llvm::Type *ST = AI.canHaveCoerceToType() 3859 ? AI.getCoerceToType() 3860 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy); 3861 llvm::Value *V; 3862 Address Tmp = CGF.CreateMemTemp(Ty); 3863 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 3864 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 3865 RegAddrLo, ST->getStructElementType(0))); 3866 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 3867 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 3868 RegAddrHi, ST->getStructElementType(1))); 3869 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 3870 3871 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 3872 } 3873 3874 // AMD64-ABI 3.5.7p5: Step 5. Set: 3875 // l->gp_offset = l->gp_offset + num_gp * 8 3876 // l->fp_offset = l->fp_offset + num_fp * 16. 3877 if (neededInt) { 3878 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); 3879 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), 3880 gp_offset_p); 3881 } 3882 if (neededSSE) { 3883 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); 3884 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), 3885 fp_offset_p); 3886 } 3887 CGF.EmitBranch(ContBlock); 3888 3889 // Emit code to load the value if it was passed in memory. 3890 3891 CGF.EmitBlock(InMemBlock); 3892 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 3893 3894 // Return the appropriate result. 3895 3896 CGF.EmitBlock(ContBlock); 3897 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock, 3898 "vaarg.addr"); 3899 return ResAddr; 3900 } 3901 3902 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 3903 QualType Ty) const { 3904 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 3905 CGF.getContext().getTypeInfoInChars(Ty), 3906 CharUnits::fromQuantity(8), 3907 /*allowHigherAlign*/ false); 3908 } 3909 3910 ABIArgInfo 3911 WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs, 3912 const ABIArgInfo ¤t) const { 3913 // Assumes vectorCall calling convention. 3914 const Type *Base = nullptr; 3915 uint64_t NumElts = 0; 3916 3917 if (!Ty->isBuiltinType() && !Ty->isVectorType() && 3918 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) { 3919 FreeSSERegs -= NumElts; 3920 return getDirectX86Hva(); 3921 } 3922 return current; 3923 } 3924 3925 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs, 3926 bool IsReturnType, bool IsVectorCall, 3927 bool IsRegCall) const { 3928 3929 if (Ty->isVoidType()) 3930 return ABIArgInfo::getIgnore(); 3931 3932 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3933 Ty = EnumTy->getDecl()->getIntegerType(); 3934 3935 TypeInfo Info = getContext().getTypeInfo(Ty); 3936 uint64_t Width = Info.Width; 3937 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align); 3938 3939 const RecordType *RT = Ty->getAs<RecordType>(); 3940 if (RT) { 3941 if (!IsReturnType) { 3942 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) 3943 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 3944 } 3945 3946 if (RT->getDecl()->hasFlexibleArrayMember()) 3947 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 3948 3949 } 3950 3951 const Type *Base = nullptr; 3952 uint64_t NumElts = 0; 3953 // vectorcall adds the concept of a homogenous vector aggregate, similar to 3954 // other targets. 3955 if ((IsVectorCall || IsRegCall) && 3956 isHomogeneousAggregate(Ty, Base, NumElts)) { 3957 if (IsRegCall) { 3958 if (FreeSSERegs >= NumElts) { 3959 FreeSSERegs -= NumElts; 3960 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType()) 3961 return ABIArgInfo::getDirect(); 3962 return ABIArgInfo::getExpand(); 3963 } 3964 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 3965 } else if (IsVectorCall) { 3966 if (FreeSSERegs >= NumElts && 3967 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) { 3968 FreeSSERegs -= NumElts; 3969 return ABIArgInfo::getDirect(); 3970 } else if (IsReturnType) { 3971 return ABIArgInfo::getExpand(); 3972 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) { 3973 // HVAs are delayed and reclassified in the 2nd step. 3974 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 3975 } 3976 } 3977 } 3978 3979 if (Ty->isMemberPointerType()) { 3980 // If the member pointer is represented by an LLVM int or ptr, pass it 3981 // directly. 3982 llvm::Type *LLTy = CGT.ConvertType(Ty); 3983 if (LLTy->isPointerTy() || LLTy->isIntegerTy()) 3984 return ABIArgInfo::getDirect(); 3985 } 3986 3987 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) { 3988 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 3989 // not 1, 2, 4, or 8 bytes, must be passed by reference." 3990 if (Width > 64 || !llvm::isPowerOf2_64(Width)) 3991 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 3992 3993 // Otherwise, coerce it to a small integer. 3994 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width)); 3995 } 3996 3997 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 3998 switch (BT->getKind()) { 3999 case BuiltinType::Bool: 4000 // Bool type is always extended to the ABI, other builtin types are not 4001 // extended. 4002 return ABIArgInfo::getExtend(Ty); 4003 4004 case BuiltinType::LongDouble: 4005 // Mingw64 GCC uses the old 80 bit extended precision floating point 4006 // unit. It passes them indirectly through memory. 4007 if (IsMingw64) { 4008 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 4009 if (LDF == &llvm::APFloat::x87DoubleExtended()) 4010 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4011 } 4012 break; 4013 4014 case BuiltinType::Int128: 4015 case BuiltinType::UInt128: 4016 // If it's a parameter type, the normal ABI rule is that arguments larger 4017 // than 8 bytes are passed indirectly. GCC follows it. We follow it too, 4018 // even though it isn't particularly efficient. 4019 if (!IsReturnType) 4020 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4021 4022 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that. 4023 // Clang matches them for compatibility. 4024 return ABIArgInfo::getDirect( 4025 llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()), 2)); 4026 4027 default: 4028 break; 4029 } 4030 } 4031 4032 return ABIArgInfo::getDirect(); 4033 } 4034 4035 void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, 4036 unsigned FreeSSERegs, 4037 bool IsVectorCall, 4038 bool IsRegCall) const { 4039 unsigned Count = 0; 4040 for (auto &I : FI.arguments()) { 4041 // Vectorcall in x64 only permits the first 6 arguments to be passed 4042 // as XMM/YMM registers. 4043 if (Count < VectorcallMaxParamNumAsReg) 4044 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall); 4045 else { 4046 // Since these cannot be passed in registers, pretend no registers 4047 // are left. 4048 unsigned ZeroSSERegsAvail = 0; 4049 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false, 4050 IsVectorCall, IsRegCall); 4051 } 4052 ++Count; 4053 } 4054 4055 for (auto &I : FI.arguments()) { 4056 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info); 4057 } 4058 } 4059 4060 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 4061 const unsigned CC = FI.getCallingConvention(); 4062 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall; 4063 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall; 4064 4065 // If __attribute__((sysv_abi)) is in use, use the SysV argument 4066 // classification rules. 4067 if (CC == llvm::CallingConv::X86_64_SysV) { 4068 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel); 4069 SysVABIInfo.computeInfo(FI); 4070 return; 4071 } 4072 4073 unsigned FreeSSERegs = 0; 4074 if (IsVectorCall) { 4075 // We can use up to 4 SSE return registers with vectorcall. 4076 FreeSSERegs = 4; 4077 } else if (IsRegCall) { 4078 // RegCall gives us 16 SSE registers. 4079 FreeSSERegs = 16; 4080 } 4081 4082 if (!getCXXABI().classifyReturnType(FI)) 4083 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true, 4084 IsVectorCall, IsRegCall); 4085 4086 if (IsVectorCall) { 4087 // We can use up to 6 SSE register parameters with vectorcall. 4088 FreeSSERegs = 6; 4089 } else if (IsRegCall) { 4090 // RegCall gives us 16 SSE registers, we can reuse the return registers. 4091 FreeSSERegs = 16; 4092 } 4093 4094 if (IsVectorCall) { 4095 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall); 4096 } else { 4097 for (auto &I : FI.arguments()) 4098 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall); 4099 } 4100 4101 } 4102 4103 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4104 QualType Ty) const { 4105 4106 bool IsIndirect = false; 4107 4108 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4109 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4110 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) { 4111 uint64_t Width = getContext().getTypeSize(Ty); 4112 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width); 4113 } 4114 4115 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 4116 CGF.getContext().getTypeInfoInChars(Ty), 4117 CharUnits::fromQuantity(8), 4118 /*allowHigherAlign*/ false); 4119 } 4120 4121 // PowerPC-32 4122 namespace { 4123 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information. 4124 class PPC32_SVR4_ABIInfo : public DefaultABIInfo { 4125 bool IsSoftFloatABI; 4126 bool IsRetSmallStructInRegABI; 4127 4128 CharUnits getParamTypeAlignment(QualType Ty) const; 4129 4130 public: 4131 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI, 4132 bool RetSmallStructInRegABI) 4133 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI), 4134 IsRetSmallStructInRegABI(RetSmallStructInRegABI) {} 4135 4136 ABIArgInfo classifyReturnType(QualType RetTy) const; 4137 4138 void computeInfo(CGFunctionInfo &FI) const override { 4139 if (!getCXXABI().classifyReturnType(FI)) 4140 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4141 for (auto &I : FI.arguments()) 4142 I.info = classifyArgumentType(I.type); 4143 } 4144 4145 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4146 QualType Ty) const override; 4147 }; 4148 4149 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo { 4150 public: 4151 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI, 4152 bool RetSmallStructInRegABI) 4153 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI, 4154 RetSmallStructInRegABI)) {} 4155 4156 static bool isStructReturnInRegABI(const llvm::Triple &Triple, 4157 const CodeGenOptions &Opts); 4158 4159 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4160 // This is recovered from gcc output. 4161 return 1; // r1 is the dedicated stack pointer 4162 } 4163 4164 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4165 llvm::Value *Address) const override; 4166 }; 4167 } 4168 4169 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 4170 // Complex types are passed just like their elements 4171 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4172 Ty = CTy->getElementType(); 4173 4174 if (Ty->isVectorType()) 4175 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 4176 : 4); 4177 4178 // For single-element float/vector structs, we consider the whole type 4179 // to have the same alignment requirements as its single element. 4180 const Type *AlignTy = nullptr; 4181 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) { 4182 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 4183 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || 4184 (BT && BT->isFloatingPoint())) 4185 AlignTy = EltType; 4186 } 4187 4188 if (AlignTy) 4189 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4); 4190 return CharUnits::fromQuantity(4); 4191 } 4192 4193 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 4194 uint64_t Size; 4195 4196 // -msvr4-struct-return puts small aggregates in GPR3 and GPR4. 4197 if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI && 4198 (Size = getContext().getTypeSize(RetTy)) <= 64) { 4199 // System V ABI (1995), page 3-22, specified: 4200 // > A structure or union whose size is less than or equal to 8 bytes 4201 // > shall be returned in r3 and r4, as if it were first stored in the 4202 // > 8-byte aligned memory area and then the low addressed word were 4203 // > loaded into r3 and the high-addressed word into r4. Bits beyond 4204 // > the last member of the structure or union are not defined. 4205 // 4206 // GCC for big-endian PPC32 inserts the pad before the first member, 4207 // not "beyond the last member" of the struct. To stay compatible 4208 // with GCC, we coerce the struct to an integer of the same size. 4209 // LLVM will extend it and return i32 in r3, or i64 in r3:r4. 4210 if (Size == 0) 4211 return ABIArgInfo::getIgnore(); 4212 else { 4213 llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size); 4214 return ABIArgInfo::getDirect(CoerceTy); 4215 } 4216 } 4217 4218 return DefaultABIInfo::classifyReturnType(RetTy); 4219 } 4220 4221 // TODO: this implementation is now likely redundant with 4222 // DefaultABIInfo::EmitVAArg. 4223 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, 4224 QualType Ty) const { 4225 if (getTarget().getTriple().isOSDarwin()) { 4226 auto TI = getContext().getTypeInfoInChars(Ty); 4227 TI.second = getParamTypeAlignment(Ty); 4228 4229 CharUnits SlotSize = CharUnits::fromQuantity(4); 4230 return emitVoidPtrVAArg(CGF, VAList, Ty, 4231 classifyArgumentType(Ty).isIndirect(), TI, SlotSize, 4232 /*AllowHigherAlign=*/true); 4233 } 4234 4235 const unsigned OverflowLimit = 8; 4236 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 4237 // TODO: Implement this. For now ignore. 4238 (void)CTy; 4239 return Address::invalid(); // FIXME? 4240 } 4241 4242 // struct __va_list_tag { 4243 // unsigned char gpr; 4244 // unsigned char fpr; 4245 // unsigned short reserved; 4246 // void *overflow_arg_area; 4247 // void *reg_save_area; 4248 // }; 4249 4250 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64; 4251 bool isInt = !Ty->isFloatingType(); 4252 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64; 4253 4254 // All aggregates are passed indirectly? That doesn't seem consistent 4255 // with the argument-lowering code. 4256 bool isIndirect = isAggregateTypeForABI(Ty); 4257 4258 CGBuilderTy &Builder = CGF.Builder; 4259 4260 // The calling convention either uses 1-2 GPRs or 1 FPR. 4261 Address NumRegsAddr = Address::invalid(); 4262 if (isInt || IsSoftFloatABI) { 4263 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr"); 4264 } else { 4265 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr"); 4266 } 4267 4268 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs"); 4269 4270 // "Align" the register count when TY is i64. 4271 if (isI64 || (isF64 && IsSoftFloatABI)) { 4272 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1)); 4273 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U)); 4274 } 4275 4276 llvm::Value *CC = 4277 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond"); 4278 4279 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs"); 4280 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow"); 4281 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 4282 4283 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow); 4284 4285 llvm::Type *DirectTy = CGF.ConvertType(Ty); 4286 if (isIndirect) DirectTy = DirectTy->getPointerTo(0); 4287 4288 // Case 1: consume registers. 4289 Address RegAddr = Address::invalid(); 4290 { 4291 CGF.EmitBlock(UsingRegs); 4292 4293 Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4); 4294 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr), 4295 CharUnits::fromQuantity(8)); 4296 assert(RegAddr.getElementType() == CGF.Int8Ty); 4297 4298 // Floating-point registers start after the general-purpose registers. 4299 if (!(isInt || IsSoftFloatABI)) { 4300 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr, 4301 CharUnits::fromQuantity(32)); 4302 } 4303 4304 // Get the address of the saved value by scaling the number of 4305 // registers we've used by the number of 4306 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8); 4307 llvm::Value *RegOffset = 4308 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity())); 4309 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty, 4310 RegAddr.getPointer(), RegOffset), 4311 RegAddr.getAlignment().alignmentOfArrayElement(RegSize)); 4312 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy); 4313 4314 // Increase the used-register count. 4315 NumRegs = 4316 Builder.CreateAdd(NumRegs, 4317 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1)); 4318 Builder.CreateStore(NumRegs, NumRegsAddr); 4319 4320 CGF.EmitBranch(Cont); 4321 } 4322 4323 // Case 2: consume space in the overflow area. 4324 Address MemAddr = Address::invalid(); 4325 { 4326 CGF.EmitBlock(UsingOverflow); 4327 4328 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr); 4329 4330 // Everything in the overflow area is rounded up to a size of at least 4. 4331 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4); 4332 4333 CharUnits Size; 4334 if (!isIndirect) { 4335 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty); 4336 Size = TypeInfo.first.alignTo(OverflowAreaAlign); 4337 } else { 4338 Size = CGF.getPointerSize(); 4339 } 4340 4341 Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3); 4342 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"), 4343 OverflowAreaAlign); 4344 // Round up address of argument to alignment 4345 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 4346 if (Align > OverflowAreaAlign) { 4347 llvm::Value *Ptr = OverflowArea.getPointer(); 4348 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align), 4349 Align); 4350 } 4351 4352 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy); 4353 4354 // Increase the overflow area. 4355 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size); 4356 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr); 4357 CGF.EmitBranch(Cont); 4358 } 4359 4360 CGF.EmitBlock(Cont); 4361 4362 // Merge the cases with a phi. 4363 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow, 4364 "vaarg.addr"); 4365 4366 // Load the pointer if the argument was passed indirectly. 4367 if (isIndirect) { 4368 Result = Address(Builder.CreateLoad(Result, "aggr"), 4369 getContext().getTypeAlignInChars(Ty)); 4370 } 4371 4372 return Result; 4373 } 4374 4375 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI( 4376 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 4377 assert(Triple.getArch() == llvm::Triple::ppc); 4378 4379 switch (Opts.getStructReturnConvention()) { 4380 case CodeGenOptions::SRCK_Default: 4381 break; 4382 case CodeGenOptions::SRCK_OnStack: // -maix-struct-return 4383 return false; 4384 case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return 4385 return true; 4386 } 4387 4388 if (Triple.isOSBinFormatELF() && !Triple.isOSLinux()) 4389 return true; 4390 4391 return false; 4392 } 4393 4394 bool 4395 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4396 llvm::Value *Address) const { 4397 // This is calculated from the LLVM and GCC tables and verified 4398 // against gcc output. AFAIK all ABIs use the same encoding. 4399 4400 CodeGen::CGBuilderTy &Builder = CGF.Builder; 4401 4402 llvm::IntegerType *i8 = CGF.Int8Ty; 4403 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 4404 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 4405 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 4406 4407 // 0-31: r0-31, the 4-byte general-purpose registers 4408 AssignToArrayRange(Builder, Address, Four8, 0, 31); 4409 4410 // 32-63: fp0-31, the 8-byte floating-point registers 4411 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 4412 4413 // 64-76 are various 4-byte special-purpose registers: 4414 // 64: mq 4415 // 65: lr 4416 // 66: ctr 4417 // 67: ap 4418 // 68-75 cr0-7 4419 // 76: xer 4420 AssignToArrayRange(Builder, Address, Four8, 64, 76); 4421 4422 // 77-108: v0-31, the 16-byte vector registers 4423 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 4424 4425 // 109: vrsave 4426 // 110: vscr 4427 // 111: spe_acc 4428 // 112: spefscr 4429 // 113: sfp 4430 AssignToArrayRange(Builder, Address, Four8, 109, 113); 4431 4432 return false; 4433 } 4434 4435 // PowerPC-64 4436 4437 namespace { 4438 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information. 4439 class PPC64_SVR4_ABIInfo : public SwiftABIInfo { 4440 public: 4441 enum ABIKind { 4442 ELFv1 = 0, 4443 ELFv2 4444 }; 4445 4446 private: 4447 static const unsigned GPRBits = 64; 4448 ABIKind Kind; 4449 bool HasQPX; 4450 bool IsSoftFloatABI; 4451 4452 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and 4453 // will be passed in a QPX register. 4454 bool IsQPXVectorTy(const Type *Ty) const { 4455 if (!HasQPX) 4456 return false; 4457 4458 if (const VectorType *VT = Ty->getAs<VectorType>()) { 4459 unsigned NumElements = VT->getNumElements(); 4460 if (NumElements == 1) 4461 return false; 4462 4463 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) { 4464 if (getContext().getTypeSize(Ty) <= 256) 4465 return true; 4466 } else if (VT->getElementType()-> 4467 isSpecificBuiltinType(BuiltinType::Float)) { 4468 if (getContext().getTypeSize(Ty) <= 128) 4469 return true; 4470 } 4471 } 4472 4473 return false; 4474 } 4475 4476 bool IsQPXVectorTy(QualType Ty) const { 4477 return IsQPXVectorTy(Ty.getTypePtr()); 4478 } 4479 4480 public: 4481 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX, 4482 bool SoftFloatABI) 4483 : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX), 4484 IsSoftFloatABI(SoftFloatABI) {} 4485 4486 bool isPromotableTypeForABI(QualType Ty) const; 4487 CharUnits getParamTypeAlignment(QualType Ty) const; 4488 4489 ABIArgInfo classifyReturnType(QualType RetTy) const; 4490 ABIArgInfo classifyArgumentType(QualType Ty) const; 4491 4492 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 4493 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 4494 uint64_t Members) const override; 4495 4496 // TODO: We can add more logic to computeInfo to improve performance. 4497 // Example: For aggregate arguments that fit in a register, we could 4498 // use getDirectInReg (as is done below for structs containing a single 4499 // floating-point value) to avoid pushing them to memory on function 4500 // entry. This would require changing the logic in PPCISelLowering 4501 // when lowering the parameters in the caller and args in the callee. 4502 void computeInfo(CGFunctionInfo &FI) const override { 4503 if (!getCXXABI().classifyReturnType(FI)) 4504 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4505 for (auto &I : FI.arguments()) { 4506 // We rely on the default argument classification for the most part. 4507 // One exception: An aggregate containing a single floating-point 4508 // or vector item must be passed in a register if one is available. 4509 const Type *T = isSingleElementStruct(I.type, getContext()); 4510 if (T) { 4511 const BuiltinType *BT = T->getAs<BuiltinType>(); 4512 if (IsQPXVectorTy(T) || 4513 (T->isVectorType() && getContext().getTypeSize(T) == 128) || 4514 (BT && BT->isFloatingPoint())) { 4515 QualType QT(T, 0); 4516 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT)); 4517 continue; 4518 } 4519 } 4520 I.info = classifyArgumentType(I.type); 4521 } 4522 } 4523 4524 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4525 QualType Ty) const override; 4526 4527 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 4528 bool asReturnValue) const override { 4529 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 4530 } 4531 4532 bool isSwiftErrorInRegister() const override { 4533 return false; 4534 } 4535 }; 4536 4537 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo { 4538 4539 public: 4540 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT, 4541 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX, 4542 bool SoftFloatABI) 4543 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX, 4544 SoftFloatABI)) {} 4545 4546 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4547 // This is recovered from gcc output. 4548 return 1; // r1 is the dedicated stack pointer 4549 } 4550 4551 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4552 llvm::Value *Address) const override; 4553 }; 4554 4555 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 4556 public: 4557 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 4558 4559 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4560 // This is recovered from gcc output. 4561 return 1; // r1 is the dedicated stack pointer 4562 } 4563 4564 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4565 llvm::Value *Address) const override; 4566 }; 4567 4568 } 4569 4570 // Return true if the ABI requires Ty to be passed sign- or zero- 4571 // extended to 64 bits. 4572 bool 4573 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const { 4574 // Treat an enum type as its underlying type. 4575 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4576 Ty = EnumTy->getDecl()->getIntegerType(); 4577 4578 // Promotable integer types are required to be promoted by the ABI. 4579 if (Ty->isPromotableIntegerType()) 4580 return true; 4581 4582 // In addition to the usual promotable integer types, we also need to 4583 // extend all 32-bit types, since the ABI requires promotion to 64 bits. 4584 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4585 switch (BT->getKind()) { 4586 case BuiltinType::Int: 4587 case BuiltinType::UInt: 4588 return true; 4589 default: 4590 break; 4591 } 4592 4593 return false; 4594 } 4595 4596 /// isAlignedParamType - Determine whether a type requires 16-byte or 4597 /// higher alignment in the parameter area. Always returns at least 8. 4598 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 4599 // Complex types are passed just like their elements. 4600 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4601 Ty = CTy->getElementType(); 4602 4603 // Only vector types of size 16 bytes need alignment (larger types are 4604 // passed via reference, smaller types are not aligned). 4605 if (IsQPXVectorTy(Ty)) { 4606 if (getContext().getTypeSize(Ty) > 128) 4607 return CharUnits::fromQuantity(32); 4608 4609 return CharUnits::fromQuantity(16); 4610 } else if (Ty->isVectorType()) { 4611 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8); 4612 } 4613 4614 // For single-element float/vector structs, we consider the whole type 4615 // to have the same alignment requirements as its single element. 4616 const Type *AlignAsType = nullptr; 4617 const Type *EltType = isSingleElementStruct(Ty, getContext()); 4618 if (EltType) { 4619 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 4620 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() && 4621 getContext().getTypeSize(EltType) == 128) || 4622 (BT && BT->isFloatingPoint())) 4623 AlignAsType = EltType; 4624 } 4625 4626 // Likewise for ELFv2 homogeneous aggregates. 4627 const Type *Base = nullptr; 4628 uint64_t Members = 0; 4629 if (!AlignAsType && Kind == ELFv2 && 4630 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members)) 4631 AlignAsType = Base; 4632 4633 // With special case aggregates, only vector base types need alignment. 4634 if (AlignAsType && IsQPXVectorTy(AlignAsType)) { 4635 if (getContext().getTypeSize(AlignAsType) > 128) 4636 return CharUnits::fromQuantity(32); 4637 4638 return CharUnits::fromQuantity(16); 4639 } else if (AlignAsType) { 4640 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8); 4641 } 4642 4643 // Otherwise, we only need alignment for any aggregate type that 4644 // has an alignment requirement of >= 16 bytes. 4645 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) { 4646 if (HasQPX && getContext().getTypeAlign(Ty) >= 256) 4647 return CharUnits::fromQuantity(32); 4648 return CharUnits::fromQuantity(16); 4649 } 4650 4651 return CharUnits::fromQuantity(8); 4652 } 4653 4654 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous 4655 /// aggregate. Base is set to the base element type, and Members is set 4656 /// to the number of base elements. 4657 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base, 4658 uint64_t &Members) const { 4659 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 4660 uint64_t NElements = AT->getSize().getZExtValue(); 4661 if (NElements == 0) 4662 return false; 4663 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members)) 4664 return false; 4665 Members *= NElements; 4666 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 4667 const RecordDecl *RD = RT->getDecl(); 4668 if (RD->hasFlexibleArrayMember()) 4669 return false; 4670 4671 Members = 0; 4672 4673 // If this is a C++ record, check the bases first. 4674 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 4675 for (const auto &I : CXXRD->bases()) { 4676 // Ignore empty records. 4677 if (isEmptyRecord(getContext(), I.getType(), true)) 4678 continue; 4679 4680 uint64_t FldMembers; 4681 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers)) 4682 return false; 4683 4684 Members += FldMembers; 4685 } 4686 } 4687 4688 for (const auto *FD : RD->fields()) { 4689 // Ignore (non-zero arrays of) empty records. 4690 QualType FT = FD->getType(); 4691 while (const ConstantArrayType *AT = 4692 getContext().getAsConstantArrayType(FT)) { 4693 if (AT->getSize().getZExtValue() == 0) 4694 return false; 4695 FT = AT->getElementType(); 4696 } 4697 if (isEmptyRecord(getContext(), FT, true)) 4698 continue; 4699 4700 // For compatibility with GCC, ignore empty bitfields in C++ mode. 4701 if (getContext().getLangOpts().CPlusPlus && 4702 FD->isZeroLengthBitField(getContext())) 4703 continue; 4704 4705 uint64_t FldMembers; 4706 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers)) 4707 return false; 4708 4709 Members = (RD->isUnion() ? 4710 std::max(Members, FldMembers) : Members + FldMembers); 4711 } 4712 4713 if (!Base) 4714 return false; 4715 4716 // Ensure there is no padding. 4717 if (getContext().getTypeSize(Base) * Members != 4718 getContext().getTypeSize(Ty)) 4719 return false; 4720 } else { 4721 Members = 1; 4722 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 4723 Members = 2; 4724 Ty = CT->getElementType(); 4725 } 4726 4727 // Most ABIs only support float, double, and some vector type widths. 4728 if (!isHomogeneousAggregateBaseType(Ty)) 4729 return false; 4730 4731 // The base type must be the same for all members. Types that 4732 // agree in both total size and mode (float vs. vector) are 4733 // treated as being equivalent here. 4734 const Type *TyPtr = Ty.getTypePtr(); 4735 if (!Base) { 4736 Base = TyPtr; 4737 // If it's a non-power-of-2 vector, its size is already a power-of-2, 4738 // so make sure to widen it explicitly. 4739 if (const VectorType *VT = Base->getAs<VectorType>()) { 4740 QualType EltTy = VT->getElementType(); 4741 unsigned NumElements = 4742 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy); 4743 Base = getContext() 4744 .getVectorType(EltTy, NumElements, VT->getVectorKind()) 4745 .getTypePtr(); 4746 } 4747 } 4748 4749 if (Base->isVectorType() != TyPtr->isVectorType() || 4750 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr)) 4751 return false; 4752 } 4753 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members); 4754 } 4755 4756 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 4757 // Homogeneous aggregates for ELFv2 must have base types of float, 4758 // double, long double, or 128-bit vectors. 4759 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 4760 if (BT->getKind() == BuiltinType::Float || 4761 BT->getKind() == BuiltinType::Double || 4762 BT->getKind() == BuiltinType::LongDouble || 4763 (getContext().getTargetInfo().hasFloat128Type() && 4764 (BT->getKind() == BuiltinType::Float128))) { 4765 if (IsSoftFloatABI) 4766 return false; 4767 return true; 4768 } 4769 } 4770 if (const VectorType *VT = Ty->getAs<VectorType>()) { 4771 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty)) 4772 return true; 4773 } 4774 return false; 4775 } 4776 4777 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough( 4778 const Type *Base, uint64_t Members) const { 4779 // Vector and fp128 types require one register, other floating point types 4780 // require one or two registers depending on their size. 4781 uint32_t NumRegs = 4782 ((getContext().getTargetInfo().hasFloat128Type() && 4783 Base->isFloat128Type()) || 4784 Base->isVectorType()) ? 1 4785 : (getContext().getTypeSize(Base) + 63) / 64; 4786 4787 // Homogeneous Aggregates may occupy at most 8 registers. 4788 return Members * NumRegs <= 8; 4789 } 4790 4791 ABIArgInfo 4792 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const { 4793 Ty = useFirstFieldIfTransparentUnion(Ty); 4794 4795 if (Ty->isAnyComplexType()) 4796 return ABIArgInfo::getDirect(); 4797 4798 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes) 4799 // or via reference (larger than 16 bytes). 4800 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) { 4801 uint64_t Size = getContext().getTypeSize(Ty); 4802 if (Size > 128) 4803 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4804 else if (Size < 128) { 4805 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 4806 return ABIArgInfo::getDirect(CoerceTy); 4807 } 4808 } 4809 4810 if (isAggregateTypeForABI(Ty)) { 4811 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 4812 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4813 4814 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity(); 4815 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 4816 4817 // ELFv2 homogeneous aggregates are passed as array types. 4818 const Type *Base = nullptr; 4819 uint64_t Members = 0; 4820 if (Kind == ELFv2 && 4821 isHomogeneousAggregate(Ty, Base, Members)) { 4822 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 4823 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 4824 return ABIArgInfo::getDirect(CoerceTy); 4825 } 4826 4827 // If an aggregate may end up fully in registers, we do not 4828 // use the ByVal method, but pass the aggregate as array. 4829 // This is usually beneficial since we avoid forcing the 4830 // back-end to store the argument to memory. 4831 uint64_t Bits = getContext().getTypeSize(Ty); 4832 if (Bits > 0 && Bits <= 8 * GPRBits) { 4833 llvm::Type *CoerceTy; 4834 4835 // Types up to 8 bytes are passed as integer type (which will be 4836 // properly aligned in the argument save area doubleword). 4837 if (Bits <= GPRBits) 4838 CoerceTy = 4839 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 4840 // Larger types are passed as arrays, with the base type selected 4841 // according to the required alignment in the save area. 4842 else { 4843 uint64_t RegBits = ABIAlign * 8; 4844 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits; 4845 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits); 4846 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs); 4847 } 4848 4849 return ABIArgInfo::getDirect(CoerceTy); 4850 } 4851 4852 // All other aggregates are passed ByVal. 4853 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 4854 /*ByVal=*/true, 4855 /*Realign=*/TyAlign > ABIAlign); 4856 } 4857 4858 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 4859 : ABIArgInfo::getDirect()); 4860 } 4861 4862 ABIArgInfo 4863 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 4864 if (RetTy->isVoidType()) 4865 return ABIArgInfo::getIgnore(); 4866 4867 if (RetTy->isAnyComplexType()) 4868 return ABIArgInfo::getDirect(); 4869 4870 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes) 4871 // or via reference (larger than 16 bytes). 4872 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) { 4873 uint64_t Size = getContext().getTypeSize(RetTy); 4874 if (Size > 128) 4875 return getNaturalAlignIndirect(RetTy); 4876 else if (Size < 128) { 4877 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 4878 return ABIArgInfo::getDirect(CoerceTy); 4879 } 4880 } 4881 4882 if (isAggregateTypeForABI(RetTy)) { 4883 // ELFv2 homogeneous aggregates are returned as array types. 4884 const Type *Base = nullptr; 4885 uint64_t Members = 0; 4886 if (Kind == ELFv2 && 4887 isHomogeneousAggregate(RetTy, Base, Members)) { 4888 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 4889 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 4890 return ABIArgInfo::getDirect(CoerceTy); 4891 } 4892 4893 // ELFv2 small aggregates are returned in up to two registers. 4894 uint64_t Bits = getContext().getTypeSize(RetTy); 4895 if (Kind == ELFv2 && Bits <= 2 * GPRBits) { 4896 if (Bits == 0) 4897 return ABIArgInfo::getIgnore(); 4898 4899 llvm::Type *CoerceTy; 4900 if (Bits > GPRBits) { 4901 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits); 4902 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy); 4903 } else 4904 CoerceTy = 4905 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 4906 return ABIArgInfo::getDirect(CoerceTy); 4907 } 4908 4909 // All other aggregates are returned indirectly. 4910 return getNaturalAlignIndirect(RetTy); 4911 } 4912 4913 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 4914 : ABIArgInfo::getDirect()); 4915 } 4916 4917 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine. 4918 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4919 QualType Ty) const { 4920 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 4921 TypeInfo.second = getParamTypeAlignment(Ty); 4922 4923 CharUnits SlotSize = CharUnits::fromQuantity(8); 4924 4925 // If we have a complex type and the base type is smaller than 8 bytes, 4926 // the ABI calls for the real and imaginary parts to be right-adjusted 4927 // in separate doublewords. However, Clang expects us to produce a 4928 // pointer to a structure with the two parts packed tightly. So generate 4929 // loads of the real and imaginary parts relative to the va_list pointer, 4930 // and store them to a temporary structure. 4931 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 4932 CharUnits EltSize = TypeInfo.first / 2; 4933 if (EltSize < SlotSize) { 4934 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, 4935 SlotSize * 2, SlotSize, 4936 SlotSize, /*AllowHigher*/ true); 4937 4938 Address RealAddr = Addr; 4939 Address ImagAddr = RealAddr; 4940 if (CGF.CGM.getDataLayout().isBigEndian()) { 4941 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, 4942 SlotSize - EltSize); 4943 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr, 4944 2 * SlotSize - EltSize); 4945 } else { 4946 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize); 4947 } 4948 4949 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType()); 4950 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy); 4951 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy); 4952 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal"); 4953 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag"); 4954 4955 Address Temp = CGF.CreateMemTemp(Ty, "vacplx"); 4956 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty), 4957 /*init*/ true); 4958 return Temp; 4959 } 4960 } 4961 4962 // Otherwise, just use the general rule. 4963 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 4964 TypeInfo, SlotSize, /*AllowHigher*/ true); 4965 } 4966 4967 static bool 4968 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4969 llvm::Value *Address) { 4970 // This is calculated from the LLVM and GCC tables and verified 4971 // against gcc output. AFAIK all ABIs use the same encoding. 4972 4973 CodeGen::CGBuilderTy &Builder = CGF.Builder; 4974 4975 llvm::IntegerType *i8 = CGF.Int8Ty; 4976 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 4977 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 4978 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 4979 4980 // 0-31: r0-31, the 8-byte general-purpose registers 4981 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 4982 4983 // 32-63: fp0-31, the 8-byte floating-point registers 4984 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 4985 4986 // 64-67 are various 8-byte special-purpose registers: 4987 // 64: mq 4988 // 65: lr 4989 // 66: ctr 4990 // 67: ap 4991 AssignToArrayRange(Builder, Address, Eight8, 64, 67); 4992 4993 // 68-76 are various 4-byte special-purpose registers: 4994 // 68-75 cr0-7 4995 // 76: xer 4996 AssignToArrayRange(Builder, Address, Four8, 68, 76); 4997 4998 // 77-108: v0-31, the 16-byte vector registers 4999 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 5000 5001 // 109: vrsave 5002 // 110: vscr 5003 // 111: spe_acc 5004 // 112: spefscr 5005 // 113: sfp 5006 // 114: tfhar 5007 // 115: tfiar 5008 // 116: texasr 5009 AssignToArrayRange(Builder, Address, Eight8, 109, 116); 5010 5011 return false; 5012 } 5013 5014 bool 5015 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable( 5016 CodeGen::CodeGenFunction &CGF, 5017 llvm::Value *Address) const { 5018 5019 return PPC64_initDwarfEHRegSizeTable(CGF, Address); 5020 } 5021 5022 bool 5023 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5024 llvm::Value *Address) const { 5025 5026 return PPC64_initDwarfEHRegSizeTable(CGF, Address); 5027 } 5028 5029 //===----------------------------------------------------------------------===// 5030 // AArch64 ABI Implementation 5031 //===----------------------------------------------------------------------===// 5032 5033 namespace { 5034 5035 class AArch64ABIInfo : public SwiftABIInfo { 5036 public: 5037 enum ABIKind { 5038 AAPCS = 0, 5039 DarwinPCS, 5040 Win64 5041 }; 5042 5043 private: 5044 ABIKind Kind; 5045 5046 public: 5047 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) 5048 : SwiftABIInfo(CGT), Kind(Kind) {} 5049 5050 private: 5051 ABIKind getABIKind() const { return Kind; } 5052 bool isDarwinPCS() const { return Kind == DarwinPCS; } 5053 5054 ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const; 5055 ABIArgInfo classifyArgumentType(QualType RetTy) const; 5056 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 5057 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 5058 uint64_t Members) const override; 5059 5060 bool isIllegalVectorType(QualType Ty) const; 5061 5062 void computeInfo(CGFunctionInfo &FI) const override { 5063 if (!::classifyReturnType(getCXXABI(), FI, *this)) 5064 FI.getReturnInfo() = 5065 classifyReturnType(FI.getReturnType(), FI.isVariadic()); 5066 5067 for (auto &it : FI.arguments()) 5068 it.info = classifyArgumentType(it.type); 5069 } 5070 5071 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty, 5072 CodeGenFunction &CGF) const; 5073 5074 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty, 5075 CodeGenFunction &CGF) const; 5076 5077 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5078 QualType Ty) const override { 5079 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty) 5080 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF) 5081 : EmitAAPCSVAArg(VAListAddr, Ty, CGF); 5082 } 5083 5084 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 5085 QualType Ty) const override; 5086 5087 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5088 bool asReturnValue) const override { 5089 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5090 } 5091 bool isSwiftErrorInRegister() const override { 5092 return true; 5093 } 5094 5095 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 5096 unsigned elts) const override; 5097 }; 5098 5099 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo { 5100 public: 5101 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind) 5102 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {} 5103 5104 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 5105 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue"; 5106 } 5107 5108 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5109 return 31; 5110 } 5111 5112 bool doesReturnSlotInterfereWithArgs() const override { return false; } 5113 5114 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5115 CodeGen::CodeGenModule &CGM) const override { 5116 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 5117 if (!FD) 5118 return; 5119 5120 CodeGenOptions::SignReturnAddressScope Scope = CGM.getCodeGenOpts().getSignReturnAddress(); 5121 CodeGenOptions::SignReturnAddressKeyValue Key = CGM.getCodeGenOpts().getSignReturnAddressKey(); 5122 bool BranchTargetEnforcement = CGM.getCodeGenOpts().BranchTargetEnforcement; 5123 if (const auto *TA = FD->getAttr<TargetAttr>()) { 5124 ParsedTargetAttr Attr = TA->parse(); 5125 if (!Attr.BranchProtection.empty()) { 5126 TargetInfo::BranchProtectionInfo BPI; 5127 StringRef Error; 5128 (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection, 5129 BPI, Error); 5130 assert(Error.empty()); 5131 Scope = BPI.SignReturnAddr; 5132 Key = BPI.SignKey; 5133 BranchTargetEnforcement = BPI.BranchTargetEnforcement; 5134 } 5135 } 5136 5137 auto *Fn = cast<llvm::Function>(GV); 5138 if (Scope != CodeGenOptions::SignReturnAddressScope::None) { 5139 Fn->addFnAttr("sign-return-address", 5140 Scope == CodeGenOptions::SignReturnAddressScope::All 5141 ? "all" 5142 : "non-leaf"); 5143 5144 Fn->addFnAttr("sign-return-address-key", 5145 Key == CodeGenOptions::SignReturnAddressKeyValue::AKey 5146 ? "a_key" 5147 : "b_key"); 5148 } 5149 5150 if (BranchTargetEnforcement) 5151 Fn->addFnAttr("branch-target-enforcement"); 5152 } 5153 }; 5154 5155 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo { 5156 public: 5157 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K) 5158 : AArch64TargetCodeGenInfo(CGT, K) {} 5159 5160 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5161 CodeGen::CodeGenModule &CGM) const override; 5162 5163 void getDependentLibraryOption(llvm::StringRef Lib, 5164 llvm::SmallString<24> &Opt) const override { 5165 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 5166 } 5167 5168 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 5169 llvm::SmallString<32> &Opt) const override { 5170 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 5171 } 5172 }; 5173 5174 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes( 5175 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 5176 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 5177 if (GV->isDeclaration()) 5178 return; 5179 addStackProbeTargetAttributes(D, GV, CGM); 5180 } 5181 } 5182 5183 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const { 5184 Ty = useFirstFieldIfTransparentUnion(Ty); 5185 5186 // Handle illegal vector types here. 5187 if (isIllegalVectorType(Ty)) { 5188 uint64_t Size = getContext().getTypeSize(Ty); 5189 // Android promotes <2 x i8> to i16, not i32 5190 if (isAndroid() && (Size <= 16)) { 5191 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext()); 5192 return ABIArgInfo::getDirect(ResType); 5193 } 5194 if (Size <= 32) { 5195 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext()); 5196 return ABIArgInfo::getDirect(ResType); 5197 } 5198 if (Size == 64) { 5199 llvm::Type *ResType = 5200 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2); 5201 return ABIArgInfo::getDirect(ResType); 5202 } 5203 if (Size == 128) { 5204 llvm::Type *ResType = 5205 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4); 5206 return ABIArgInfo::getDirect(ResType); 5207 } 5208 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5209 } 5210 5211 if (!isAggregateTypeForABI(Ty)) { 5212 // Treat an enum type as its underlying type. 5213 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5214 Ty = EnumTy->getDecl()->getIntegerType(); 5215 5216 return (Ty->isPromotableIntegerType() && isDarwinPCS() 5217 ? ABIArgInfo::getExtend(Ty) 5218 : ABIArgInfo::getDirect()); 5219 } 5220 5221 // Structures with either a non-trivial destructor or a non-trivial 5222 // copy constructor are always indirect. 5223 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 5224 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 5225 CGCXXABI::RAA_DirectInMemory); 5226 } 5227 5228 // Empty records are always ignored on Darwin, but actually passed in C++ mode 5229 // elsewhere for GNU compatibility. 5230 uint64_t Size = getContext().getTypeSize(Ty); 5231 bool IsEmpty = isEmptyRecord(getContext(), Ty, true); 5232 if (IsEmpty || Size == 0) { 5233 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS()) 5234 return ABIArgInfo::getIgnore(); 5235 5236 // GNU C mode. The only argument that gets ignored is an empty one with size 5237 // 0. 5238 if (IsEmpty && Size == 0) 5239 return ABIArgInfo::getIgnore(); 5240 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5241 } 5242 5243 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded. 5244 const Type *Base = nullptr; 5245 uint64_t Members = 0; 5246 if (isHomogeneousAggregate(Ty, Base, Members)) { 5247 return ABIArgInfo::getDirect( 5248 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members)); 5249 } 5250 5251 // Aggregates <= 16 bytes are passed directly in registers or on the stack. 5252 if (Size <= 128) { 5253 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5254 // same size and alignment. 5255 if (getTarget().isRenderScriptTarget()) { 5256 return coerceToIntArray(Ty, getContext(), getVMContext()); 5257 } 5258 unsigned Alignment; 5259 if (Kind == AArch64ABIInfo::AAPCS) { 5260 Alignment = getContext().getTypeUnadjustedAlign(Ty); 5261 Alignment = Alignment < 128 ? 64 : 128; 5262 } else { 5263 Alignment = std::max(getContext().getTypeAlign(Ty), 5264 (unsigned)getTarget().getPointerWidth(0)); 5265 } 5266 Size = llvm::alignTo(Size, Alignment); 5267 5268 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5269 // For aggregates with 16-byte alignment, we use i128. 5270 llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment); 5271 return ABIArgInfo::getDirect( 5272 Size == Alignment ? BaseTy 5273 : llvm::ArrayType::get(BaseTy, Size / Alignment)); 5274 } 5275 5276 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5277 } 5278 5279 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy, 5280 bool IsVariadic) const { 5281 if (RetTy->isVoidType()) 5282 return ABIArgInfo::getIgnore(); 5283 5284 // Large vector types should be returned via memory. 5285 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) 5286 return getNaturalAlignIndirect(RetTy); 5287 5288 if (!isAggregateTypeForABI(RetTy)) { 5289 // Treat an enum type as its underlying type. 5290 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 5291 RetTy = EnumTy->getDecl()->getIntegerType(); 5292 5293 return (RetTy->isPromotableIntegerType() && isDarwinPCS() 5294 ? ABIArgInfo::getExtend(RetTy) 5295 : ABIArgInfo::getDirect()); 5296 } 5297 5298 uint64_t Size = getContext().getTypeSize(RetTy); 5299 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0) 5300 return ABIArgInfo::getIgnore(); 5301 5302 const Type *Base = nullptr; 5303 uint64_t Members = 0; 5304 if (isHomogeneousAggregate(RetTy, Base, Members) && 5305 !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 && 5306 IsVariadic)) 5307 // Homogeneous Floating-point Aggregates (HFAs) are returned directly. 5308 return ABIArgInfo::getDirect(); 5309 5310 // Aggregates <= 16 bytes are returned directly in registers or on the stack. 5311 if (Size <= 128) { 5312 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5313 // same size and alignment. 5314 if (getTarget().isRenderScriptTarget()) { 5315 return coerceToIntArray(RetTy, getContext(), getVMContext()); 5316 } 5317 unsigned Alignment = getContext().getTypeAlign(RetTy); 5318 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes 5319 5320 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5321 // For aggregates with 16-byte alignment, we use i128. 5322 if (Alignment < 128 && Size == 128) { 5323 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext()); 5324 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64)); 5325 } 5326 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size)); 5327 } 5328 5329 return getNaturalAlignIndirect(RetTy); 5330 } 5331 5332 /// isIllegalVectorType - check whether the vector type is legal for AArch64. 5333 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const { 5334 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5335 // Check whether VT is legal. 5336 unsigned NumElements = VT->getNumElements(); 5337 uint64_t Size = getContext().getTypeSize(VT); 5338 // NumElements should be power of 2. 5339 if (!llvm::isPowerOf2_32(NumElements)) 5340 return true; 5341 5342 // arm64_32 has to be compatible with the ARM logic here, which allows huge 5343 // vectors for some reason. 5344 llvm::Triple Triple = getTarget().getTriple(); 5345 if (Triple.getArch() == llvm::Triple::aarch64_32 && 5346 Triple.isOSBinFormatMachO()) 5347 return Size <= 32; 5348 5349 return Size != 64 && (Size != 128 || NumElements == 1); 5350 } 5351 return false; 5352 } 5353 5354 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize, 5355 llvm::Type *eltTy, 5356 unsigned elts) const { 5357 if (!llvm::isPowerOf2_32(elts)) 5358 return false; 5359 if (totalSize.getQuantity() != 8 && 5360 (totalSize.getQuantity() != 16 || elts == 1)) 5361 return false; 5362 return true; 5363 } 5364 5365 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5366 // Homogeneous aggregates for AAPCS64 must have base types of a floating 5367 // point type or a short-vector type. This is the same as the 32-bit ABI, 5368 // but with the difference that any floating-point type is allowed, 5369 // including __fp16. 5370 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5371 if (BT->isFloatingPoint()) 5372 return true; 5373 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 5374 unsigned VecSize = getContext().getTypeSize(VT); 5375 if (VecSize == 64 || VecSize == 128) 5376 return true; 5377 } 5378 return false; 5379 } 5380 5381 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 5382 uint64_t Members) const { 5383 return Members <= 4; 5384 } 5385 5386 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, 5387 QualType Ty, 5388 CodeGenFunction &CGF) const { 5389 ABIArgInfo AI = classifyArgumentType(Ty); 5390 bool IsIndirect = AI.isIndirect(); 5391 5392 llvm::Type *BaseTy = CGF.ConvertType(Ty); 5393 if (IsIndirect) 5394 BaseTy = llvm::PointerType::getUnqual(BaseTy); 5395 else if (AI.getCoerceToType()) 5396 BaseTy = AI.getCoerceToType(); 5397 5398 unsigned NumRegs = 1; 5399 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) { 5400 BaseTy = ArrTy->getElementType(); 5401 NumRegs = ArrTy->getNumElements(); 5402 } 5403 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy(); 5404 5405 // The AArch64 va_list type and handling is specified in the Procedure Call 5406 // Standard, section B.4: 5407 // 5408 // struct { 5409 // void *__stack; 5410 // void *__gr_top; 5411 // void *__vr_top; 5412 // int __gr_offs; 5413 // int __vr_offs; 5414 // }; 5415 5416 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 5417 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 5418 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 5419 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 5420 5421 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 5422 CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty); 5423 5424 Address reg_offs_p = Address::invalid(); 5425 llvm::Value *reg_offs = nullptr; 5426 int reg_top_index; 5427 int RegSize = IsIndirect ? 8 : TySize.getQuantity(); 5428 if (!IsFPR) { 5429 // 3 is the field number of __gr_offs 5430 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p"); 5431 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs"); 5432 reg_top_index = 1; // field number for __gr_top 5433 RegSize = llvm::alignTo(RegSize, 8); 5434 } else { 5435 // 4 is the field number of __vr_offs. 5436 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p"); 5437 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs"); 5438 reg_top_index = 2; // field number for __vr_top 5439 RegSize = 16 * NumRegs; 5440 } 5441 5442 //======================================= 5443 // Find out where argument was passed 5444 //======================================= 5445 5446 // If reg_offs >= 0 we're already using the stack for this type of 5447 // argument. We don't want to keep updating reg_offs (in case it overflows, 5448 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves 5449 // whatever they get). 5450 llvm::Value *UsingStack = nullptr; 5451 UsingStack = CGF.Builder.CreateICmpSGE( 5452 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0)); 5453 5454 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock); 5455 5456 // Otherwise, at least some kind of argument could go in these registers, the 5457 // question is whether this particular type is too big. 5458 CGF.EmitBlock(MaybeRegBlock); 5459 5460 // Integer arguments may need to correct register alignment (for example a 5461 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we 5462 // align __gr_offs to calculate the potential address. 5463 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) { 5464 int Align = TyAlign.getQuantity(); 5465 5466 reg_offs = CGF.Builder.CreateAdd( 5467 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1), 5468 "align_regoffs"); 5469 reg_offs = CGF.Builder.CreateAnd( 5470 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align), 5471 "aligned_regoffs"); 5472 } 5473 5474 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list. 5475 // The fact that this is done unconditionally reflects the fact that 5476 // allocating an argument to the stack also uses up all the remaining 5477 // registers of the appropriate kind. 5478 llvm::Value *NewOffset = nullptr; 5479 NewOffset = CGF.Builder.CreateAdd( 5480 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs"); 5481 CGF.Builder.CreateStore(NewOffset, reg_offs_p); 5482 5483 // Now we're in a position to decide whether this argument really was in 5484 // registers or not. 5485 llvm::Value *InRegs = nullptr; 5486 InRegs = CGF.Builder.CreateICmpSLE( 5487 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg"); 5488 5489 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock); 5490 5491 //======================================= 5492 // Argument was in registers 5493 //======================================= 5494 5495 // Now we emit the code for if the argument was originally passed in 5496 // registers. First start the appropriate block: 5497 CGF.EmitBlock(InRegBlock); 5498 5499 llvm::Value *reg_top = nullptr; 5500 Address reg_top_p = 5501 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p"); 5502 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top"); 5503 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs), 5504 CharUnits::fromQuantity(IsFPR ? 16 : 8)); 5505 Address RegAddr = Address::invalid(); 5506 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty); 5507 5508 if (IsIndirect) { 5509 // If it's been passed indirectly (actually a struct), whatever we find from 5510 // stored registers or on the stack will actually be a struct **. 5511 MemTy = llvm::PointerType::getUnqual(MemTy); 5512 } 5513 5514 const Type *Base = nullptr; 5515 uint64_t NumMembers = 0; 5516 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers); 5517 if (IsHFA && NumMembers > 1) { 5518 // Homogeneous aggregates passed in registers will have their elements split 5519 // and stored 16-bytes apart regardless of size (they're notionally in qN, 5520 // qN+1, ...). We reload and store into a temporary local variable 5521 // contiguously. 5522 assert(!IsIndirect && "Homogeneous aggregates should be passed directly"); 5523 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0)); 5524 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0)); 5525 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers); 5526 Address Tmp = CGF.CreateTempAlloca(HFATy, 5527 std::max(TyAlign, BaseTyInfo.second)); 5528 5529 // On big-endian platforms, the value will be right-aligned in its slot. 5530 int Offset = 0; 5531 if (CGF.CGM.getDataLayout().isBigEndian() && 5532 BaseTyInfo.first.getQuantity() < 16) 5533 Offset = 16 - BaseTyInfo.first.getQuantity(); 5534 5535 for (unsigned i = 0; i < NumMembers; ++i) { 5536 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset); 5537 Address LoadAddr = 5538 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset); 5539 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy); 5540 5541 Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i); 5542 5543 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr); 5544 CGF.Builder.CreateStore(Elem, StoreAddr); 5545 } 5546 5547 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy); 5548 } else { 5549 // Otherwise the object is contiguous in memory. 5550 5551 // It might be right-aligned in its slot. 5552 CharUnits SlotSize = BaseAddr.getAlignment(); 5553 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect && 5554 (IsHFA || !isAggregateTypeForABI(Ty)) && 5555 TySize < SlotSize) { 5556 CharUnits Offset = SlotSize - TySize; 5557 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset); 5558 } 5559 5560 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy); 5561 } 5562 5563 CGF.EmitBranch(ContBlock); 5564 5565 //======================================= 5566 // Argument was on the stack 5567 //======================================= 5568 CGF.EmitBlock(OnStackBlock); 5569 5570 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p"); 5571 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack"); 5572 5573 // Again, stack arguments may need realignment. In this case both integer and 5574 // floating-point ones might be affected. 5575 if (!IsIndirect && TyAlign.getQuantity() > 8) { 5576 int Align = TyAlign.getQuantity(); 5577 5578 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty); 5579 5580 OnStackPtr = CGF.Builder.CreateAdd( 5581 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1), 5582 "align_stack"); 5583 OnStackPtr = CGF.Builder.CreateAnd( 5584 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align), 5585 "align_stack"); 5586 5587 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy); 5588 } 5589 Address OnStackAddr(OnStackPtr, 5590 std::max(CharUnits::fromQuantity(8), TyAlign)); 5591 5592 // All stack slots are multiples of 8 bytes. 5593 CharUnits StackSlotSize = CharUnits::fromQuantity(8); 5594 CharUnits StackSize; 5595 if (IsIndirect) 5596 StackSize = StackSlotSize; 5597 else 5598 StackSize = TySize.alignTo(StackSlotSize); 5599 5600 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize); 5601 llvm::Value *NewStack = 5602 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack"); 5603 5604 // Write the new value of __stack for the next call to va_arg 5605 CGF.Builder.CreateStore(NewStack, stack_p); 5606 5607 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) && 5608 TySize < StackSlotSize) { 5609 CharUnits Offset = StackSlotSize - TySize; 5610 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset); 5611 } 5612 5613 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy); 5614 5615 CGF.EmitBranch(ContBlock); 5616 5617 //======================================= 5618 // Tidy up 5619 //======================================= 5620 CGF.EmitBlock(ContBlock); 5621 5622 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 5623 OnStackAddr, OnStackBlock, "vaargs.addr"); 5624 5625 if (IsIndirect) 5626 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"), 5627 TyAlign); 5628 5629 return ResAddr; 5630 } 5631 5632 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty, 5633 CodeGenFunction &CGF) const { 5634 // The backend's lowering doesn't support va_arg for aggregates or 5635 // illegal vector types. Lower VAArg here for these cases and use 5636 // the LLVM va_arg instruction for everything else. 5637 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty)) 5638 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 5639 5640 uint64_t PointerSize = getTarget().getPointerWidth(0) / 8; 5641 CharUnits SlotSize = CharUnits::fromQuantity(PointerSize); 5642 5643 // Empty records are ignored for parameter passing purposes. 5644 if (isEmptyRecord(getContext(), Ty, true)) { 5645 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 5646 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 5647 return Addr; 5648 } 5649 5650 // The size of the actual thing passed, which might end up just 5651 // being a pointer for indirect types. 5652 auto TyInfo = getContext().getTypeInfoInChars(Ty); 5653 5654 // Arguments bigger than 16 bytes which aren't homogeneous 5655 // aggregates should be passed indirectly. 5656 bool IsIndirect = false; 5657 if (TyInfo.first.getQuantity() > 16) { 5658 const Type *Base = nullptr; 5659 uint64_t Members = 0; 5660 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members); 5661 } 5662 5663 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 5664 TyInfo, SlotSize, /*AllowHigherAlign*/ true); 5665 } 5666 5667 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 5668 QualType Ty) const { 5669 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 5670 CGF.getContext().getTypeInfoInChars(Ty), 5671 CharUnits::fromQuantity(8), 5672 /*allowHigherAlign*/ false); 5673 } 5674 5675 //===----------------------------------------------------------------------===// 5676 // ARM ABI Implementation 5677 //===----------------------------------------------------------------------===// 5678 5679 namespace { 5680 5681 class ARMABIInfo : public SwiftABIInfo { 5682 public: 5683 enum ABIKind { 5684 APCS = 0, 5685 AAPCS = 1, 5686 AAPCS_VFP = 2, 5687 AAPCS16_VFP = 3, 5688 }; 5689 5690 private: 5691 ABIKind Kind; 5692 5693 public: 5694 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) 5695 : SwiftABIInfo(CGT), Kind(_Kind) { 5696 setCCs(); 5697 } 5698 5699 bool isEABI() const { 5700 switch (getTarget().getTriple().getEnvironment()) { 5701 case llvm::Triple::Android: 5702 case llvm::Triple::EABI: 5703 case llvm::Triple::EABIHF: 5704 case llvm::Triple::GNUEABI: 5705 case llvm::Triple::GNUEABIHF: 5706 case llvm::Triple::MuslEABI: 5707 case llvm::Triple::MuslEABIHF: 5708 return true; 5709 default: 5710 return false; 5711 } 5712 } 5713 5714 bool isEABIHF() const { 5715 switch (getTarget().getTriple().getEnvironment()) { 5716 case llvm::Triple::EABIHF: 5717 case llvm::Triple::GNUEABIHF: 5718 case llvm::Triple::MuslEABIHF: 5719 return true; 5720 default: 5721 return false; 5722 } 5723 } 5724 5725 ABIKind getABIKind() const { return Kind; } 5726 5727 private: 5728 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic, 5729 unsigned functionCallConv) const; 5730 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic, 5731 unsigned functionCallConv) const; 5732 ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base, 5733 uint64_t Members) const; 5734 ABIArgInfo coerceIllegalVector(QualType Ty) const; 5735 bool isIllegalVectorType(QualType Ty) const; 5736 bool containsAnyFP16Vectors(QualType Ty) const; 5737 5738 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 5739 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 5740 uint64_t Members) const override; 5741 5742 bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const; 5743 5744 void computeInfo(CGFunctionInfo &FI) const override; 5745 5746 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5747 QualType Ty) const override; 5748 5749 llvm::CallingConv::ID getLLVMDefaultCC() const; 5750 llvm::CallingConv::ID getABIDefaultCC() const; 5751 void setCCs(); 5752 5753 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5754 bool asReturnValue) const override { 5755 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5756 } 5757 bool isSwiftErrorInRegister() const override { 5758 return true; 5759 } 5760 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 5761 unsigned elts) const override; 5762 }; 5763 5764 class ARMTargetCodeGenInfo : public TargetCodeGenInfo { 5765 public: 5766 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 5767 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {} 5768 5769 const ARMABIInfo &getABIInfo() const { 5770 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo()); 5771 } 5772 5773 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5774 return 13; 5775 } 5776 5777 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 5778 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue"; 5779 } 5780 5781 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5782 llvm::Value *Address) const override { 5783 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 5784 5785 // 0-15 are the 16 integer registers. 5786 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15); 5787 return false; 5788 } 5789 5790 unsigned getSizeOfUnwindException() const override { 5791 if (getABIInfo().isEABI()) return 88; 5792 return TargetCodeGenInfo::getSizeOfUnwindException(); 5793 } 5794 5795 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5796 CodeGen::CodeGenModule &CGM) const override { 5797 if (GV->isDeclaration()) 5798 return; 5799 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 5800 if (!FD) 5801 return; 5802 5803 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>(); 5804 if (!Attr) 5805 return; 5806 5807 const char *Kind; 5808 switch (Attr->getInterrupt()) { 5809 case ARMInterruptAttr::Generic: Kind = ""; break; 5810 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break; 5811 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break; 5812 case ARMInterruptAttr::SWI: Kind = "SWI"; break; 5813 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break; 5814 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break; 5815 } 5816 5817 llvm::Function *Fn = cast<llvm::Function>(GV); 5818 5819 Fn->addFnAttr("interrupt", Kind); 5820 5821 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind(); 5822 if (ABI == ARMABIInfo::APCS) 5823 return; 5824 5825 // AAPCS guarantees that sp will be 8-byte aligned on any public interface, 5826 // however this is not necessarily true on taking any interrupt. Instruct 5827 // the backend to perform a realignment as part of the function prologue. 5828 llvm::AttrBuilder B; 5829 B.addStackAlignmentAttr(8); 5830 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 5831 } 5832 }; 5833 5834 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo { 5835 public: 5836 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 5837 : ARMTargetCodeGenInfo(CGT, K) {} 5838 5839 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5840 CodeGen::CodeGenModule &CGM) const override; 5841 5842 void getDependentLibraryOption(llvm::StringRef Lib, 5843 llvm::SmallString<24> &Opt) const override { 5844 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 5845 } 5846 5847 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 5848 llvm::SmallString<32> &Opt) const override { 5849 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 5850 } 5851 }; 5852 5853 void WindowsARMTargetCodeGenInfo::setTargetAttributes( 5854 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 5855 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 5856 if (GV->isDeclaration()) 5857 return; 5858 addStackProbeTargetAttributes(D, GV, CGM); 5859 } 5860 } 5861 5862 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 5863 if (!::classifyReturnType(getCXXABI(), FI, *this)) 5864 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(), 5865 FI.getCallingConvention()); 5866 5867 for (auto &I : FI.arguments()) 5868 I.info = classifyArgumentType(I.type, FI.isVariadic(), 5869 FI.getCallingConvention()); 5870 5871 5872 // Always honor user-specified calling convention. 5873 if (FI.getCallingConvention() != llvm::CallingConv::C) 5874 return; 5875 5876 llvm::CallingConv::ID cc = getRuntimeCC(); 5877 if (cc != llvm::CallingConv::C) 5878 FI.setEffectiveCallingConvention(cc); 5879 } 5880 5881 /// Return the default calling convention that LLVM will use. 5882 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const { 5883 // The default calling convention that LLVM will infer. 5884 if (isEABIHF() || getTarget().getTriple().isWatchABI()) 5885 return llvm::CallingConv::ARM_AAPCS_VFP; 5886 else if (isEABI()) 5887 return llvm::CallingConv::ARM_AAPCS; 5888 else 5889 return llvm::CallingConv::ARM_APCS; 5890 } 5891 5892 /// Return the calling convention that our ABI would like us to use 5893 /// as the C calling convention. 5894 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const { 5895 switch (getABIKind()) { 5896 case APCS: return llvm::CallingConv::ARM_APCS; 5897 case AAPCS: return llvm::CallingConv::ARM_AAPCS; 5898 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 5899 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 5900 } 5901 llvm_unreachable("bad ABI kind"); 5902 } 5903 5904 void ARMABIInfo::setCCs() { 5905 assert(getRuntimeCC() == llvm::CallingConv::C); 5906 5907 // Don't muddy up the IR with a ton of explicit annotations if 5908 // they'd just match what LLVM will infer from the triple. 5909 llvm::CallingConv::ID abiCC = getABIDefaultCC(); 5910 if (abiCC != getLLVMDefaultCC()) 5911 RuntimeCC = abiCC; 5912 } 5913 5914 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const { 5915 uint64_t Size = getContext().getTypeSize(Ty); 5916 if (Size <= 32) { 5917 llvm::Type *ResType = 5918 llvm::Type::getInt32Ty(getVMContext()); 5919 return ABIArgInfo::getDirect(ResType); 5920 } 5921 if (Size == 64 || Size == 128) { 5922 llvm::Type *ResType = llvm::VectorType::get( 5923 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 5924 return ABIArgInfo::getDirect(ResType); 5925 } 5926 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5927 } 5928 5929 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty, 5930 const Type *Base, 5931 uint64_t Members) const { 5932 assert(Base && "Base class should be set for homogeneous aggregate"); 5933 // Base can be a floating-point or a vector. 5934 if (const VectorType *VT = Base->getAs<VectorType>()) { 5935 // FP16 vectors should be converted to integer vectors 5936 if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) { 5937 uint64_t Size = getContext().getTypeSize(VT); 5938 llvm::Type *NewVecTy = llvm::VectorType::get( 5939 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 5940 llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members); 5941 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 5942 } 5943 } 5944 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false); 5945 } 5946 5947 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic, 5948 unsigned functionCallConv) const { 5949 // 6.1.2.1 The following argument types are VFP CPRCs: 5950 // A single-precision floating-point type (including promoted 5951 // half-precision types); A double-precision floating-point type; 5952 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate 5953 // with a Base Type of a single- or double-precision floating-point type, 5954 // 64-bit containerized vectors or 128-bit containerized vectors with one 5955 // to four Elements. 5956 // Variadic functions should always marshal to the base standard. 5957 bool IsAAPCS_VFP = 5958 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false); 5959 5960 Ty = useFirstFieldIfTransparentUnion(Ty); 5961 5962 // Handle illegal vector types here. 5963 if (isIllegalVectorType(Ty)) 5964 return coerceIllegalVector(Ty); 5965 5966 // _Float16 and __fp16 get passed as if it were an int or float, but with 5967 // the top 16 bits unspecified. This is not done for OpenCL as it handles the 5968 // half type natively, and does not need to interwork with AAPCS code. 5969 if ((Ty->isFloat16Type() || Ty->isHalfType()) && 5970 !getContext().getLangOpts().NativeHalfArgsAndReturns) { 5971 llvm::Type *ResType = IsAAPCS_VFP ? 5972 llvm::Type::getFloatTy(getVMContext()) : 5973 llvm::Type::getInt32Ty(getVMContext()); 5974 return ABIArgInfo::getDirect(ResType); 5975 } 5976 5977 if (!isAggregateTypeForABI(Ty)) { 5978 // Treat an enum type as its underlying type. 5979 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 5980 Ty = EnumTy->getDecl()->getIntegerType(); 5981 } 5982 5983 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 5984 : ABIArgInfo::getDirect()); 5985 } 5986 5987 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 5988 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 5989 } 5990 5991 // Ignore empty records. 5992 if (isEmptyRecord(getContext(), Ty, true)) 5993 return ABIArgInfo::getIgnore(); 5994 5995 if (IsAAPCS_VFP) { 5996 // Homogeneous Aggregates need to be expanded when we can fit the aggregate 5997 // into VFP registers. 5998 const Type *Base = nullptr; 5999 uint64_t Members = 0; 6000 if (isHomogeneousAggregate(Ty, Base, Members)) 6001 return classifyHomogeneousAggregate(Ty, Base, Members); 6002 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 6003 // WatchOS does have homogeneous aggregates. Note that we intentionally use 6004 // this convention even for a variadic function: the backend will use GPRs 6005 // if needed. 6006 const Type *Base = nullptr; 6007 uint64_t Members = 0; 6008 if (isHomogeneousAggregate(Ty, Base, Members)) { 6009 assert(Base && Members <= 4 && "unexpected homogeneous aggregate"); 6010 llvm::Type *Ty = 6011 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members); 6012 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6013 } 6014 } 6015 6016 if (getABIKind() == ARMABIInfo::AAPCS16_VFP && 6017 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) { 6018 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're 6019 // bigger than 128-bits, they get placed in space allocated by the caller, 6020 // and a pointer is passed. 6021 return ABIArgInfo::getIndirect( 6022 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false); 6023 } 6024 6025 // Support byval for ARM. 6026 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at 6027 // most 8-byte. We realign the indirect argument if type alignment is bigger 6028 // than ABI alignment. 6029 uint64_t ABIAlign = 4; 6030 uint64_t TyAlign; 6031 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6032 getABIKind() == ARMABIInfo::AAPCS) { 6033 TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 6034 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 6035 } else { 6036 TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 6037 } 6038 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { 6039 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval"); 6040 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 6041 /*ByVal=*/true, 6042 /*Realign=*/TyAlign > ABIAlign); 6043 } 6044 6045 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of 6046 // same size and alignment. 6047 if (getTarget().isRenderScriptTarget()) { 6048 return coerceToIntArray(Ty, getContext(), getVMContext()); 6049 } 6050 6051 // Otherwise, pass by coercing to a structure of the appropriate size. 6052 llvm::Type* ElemTy; 6053 unsigned SizeRegs; 6054 // FIXME: Try to match the types of the arguments more accurately where 6055 // we can. 6056 if (TyAlign <= 4) { 6057 ElemTy = llvm::Type::getInt32Ty(getVMContext()); 6058 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; 6059 } else { 6060 ElemTy = llvm::Type::getInt64Ty(getVMContext()); 6061 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64; 6062 } 6063 6064 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs)); 6065 } 6066 6067 static bool isIntegerLikeType(QualType Ty, ASTContext &Context, 6068 llvm::LLVMContext &VMContext) { 6069 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure 6070 // is called integer-like if its size is less than or equal to one word, and 6071 // the offset of each of its addressable sub-fields is zero. 6072 6073 uint64_t Size = Context.getTypeSize(Ty); 6074 6075 // Check that the type fits in a word. 6076 if (Size > 32) 6077 return false; 6078 6079 // FIXME: Handle vector types! 6080 if (Ty->isVectorType()) 6081 return false; 6082 6083 // Float types are never treated as "integer like". 6084 if (Ty->isRealFloatingType()) 6085 return false; 6086 6087 // If this is a builtin or pointer type then it is ok. 6088 if (Ty->getAs<BuiltinType>() || Ty->isPointerType()) 6089 return true; 6090 6091 // Small complex integer types are "integer like". 6092 if (const ComplexType *CT = Ty->getAs<ComplexType>()) 6093 return isIntegerLikeType(CT->getElementType(), Context, VMContext); 6094 6095 // Single element and zero sized arrays should be allowed, by the definition 6096 // above, but they are not. 6097 6098 // Otherwise, it must be a record type. 6099 const RecordType *RT = Ty->getAs<RecordType>(); 6100 if (!RT) return false; 6101 6102 // Ignore records with flexible arrays. 6103 const RecordDecl *RD = RT->getDecl(); 6104 if (RD->hasFlexibleArrayMember()) 6105 return false; 6106 6107 // Check that all sub-fields are at offset 0, and are themselves "integer 6108 // like". 6109 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 6110 6111 bool HadField = false; 6112 unsigned idx = 0; 6113 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 6114 i != e; ++i, ++idx) { 6115 const FieldDecl *FD = *i; 6116 6117 // Bit-fields are not addressable, we only need to verify they are "integer 6118 // like". We still have to disallow a subsequent non-bitfield, for example: 6119 // struct { int : 0; int x } 6120 // is non-integer like according to gcc. 6121 if (FD->isBitField()) { 6122 if (!RD->isUnion()) 6123 HadField = true; 6124 6125 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6126 return false; 6127 6128 continue; 6129 } 6130 6131 // Check if this field is at offset 0. 6132 if (Layout.getFieldOffset(idx) != 0) 6133 return false; 6134 6135 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6136 return false; 6137 6138 // Only allow at most one field in a structure. This doesn't match the 6139 // wording above, but follows gcc in situations with a field following an 6140 // empty structure. 6141 if (!RD->isUnion()) { 6142 if (HadField) 6143 return false; 6144 6145 HadField = true; 6146 } 6147 } 6148 6149 return true; 6150 } 6151 6152 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic, 6153 unsigned functionCallConv) const { 6154 6155 // Variadic functions should always marshal to the base standard. 6156 bool IsAAPCS_VFP = 6157 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true); 6158 6159 if (RetTy->isVoidType()) 6160 return ABIArgInfo::getIgnore(); 6161 6162 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 6163 // Large vector types should be returned via memory. 6164 if (getContext().getTypeSize(RetTy) > 128) 6165 return getNaturalAlignIndirect(RetTy); 6166 // FP16 vectors should be converted to integer vectors 6167 if (!getTarget().hasLegalHalfType() && 6168 (VT->getElementType()->isFloat16Type() || 6169 VT->getElementType()->isHalfType())) 6170 return coerceIllegalVector(RetTy); 6171 } 6172 6173 // _Float16 and __fp16 get returned as if it were an int or float, but with 6174 // the top 16 bits unspecified. This is not done for OpenCL as it handles the 6175 // half type natively, and does not need to interwork with AAPCS code. 6176 if ((RetTy->isFloat16Type() || RetTy->isHalfType()) && 6177 !getContext().getLangOpts().NativeHalfArgsAndReturns) { 6178 llvm::Type *ResType = IsAAPCS_VFP ? 6179 llvm::Type::getFloatTy(getVMContext()) : 6180 llvm::Type::getInt32Ty(getVMContext()); 6181 return ABIArgInfo::getDirect(ResType); 6182 } 6183 6184 if (!isAggregateTypeForABI(RetTy)) { 6185 // Treat an enum type as its underlying type. 6186 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 6187 RetTy = EnumTy->getDecl()->getIntegerType(); 6188 6189 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 6190 : ABIArgInfo::getDirect(); 6191 } 6192 6193 // Are we following APCS? 6194 if (getABIKind() == APCS) { 6195 if (isEmptyRecord(getContext(), RetTy, false)) 6196 return ABIArgInfo::getIgnore(); 6197 6198 // Complex types are all returned as packed integers. 6199 // 6200 // FIXME: Consider using 2 x vector types if the back end handles them 6201 // correctly. 6202 if (RetTy->isAnyComplexType()) 6203 return ABIArgInfo::getDirect(llvm::IntegerType::get( 6204 getVMContext(), getContext().getTypeSize(RetTy))); 6205 6206 // Integer like structures are returned in r0. 6207 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) { 6208 // Return in the smallest viable integer type. 6209 uint64_t Size = getContext().getTypeSize(RetTy); 6210 if (Size <= 8) 6211 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6212 if (Size <= 16) 6213 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6214 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6215 } 6216 6217 // Otherwise return in memory. 6218 return getNaturalAlignIndirect(RetTy); 6219 } 6220 6221 // Otherwise this is an AAPCS variant. 6222 6223 if (isEmptyRecord(getContext(), RetTy, true)) 6224 return ABIArgInfo::getIgnore(); 6225 6226 // Check for homogeneous aggregates with AAPCS-VFP. 6227 if (IsAAPCS_VFP) { 6228 const Type *Base = nullptr; 6229 uint64_t Members = 0; 6230 if (isHomogeneousAggregate(RetTy, Base, Members)) 6231 return classifyHomogeneousAggregate(RetTy, Base, Members); 6232 } 6233 6234 // Aggregates <= 4 bytes are returned in r0; other aggregates 6235 // are returned indirectly. 6236 uint64_t Size = getContext().getTypeSize(RetTy); 6237 if (Size <= 32) { 6238 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of 6239 // same size and alignment. 6240 if (getTarget().isRenderScriptTarget()) { 6241 return coerceToIntArray(RetTy, getContext(), getVMContext()); 6242 } 6243 if (getDataLayout().isBigEndian()) 6244 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4) 6245 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6246 6247 // Return in the smallest viable integer type. 6248 if (Size <= 8) 6249 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6250 if (Size <= 16) 6251 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6252 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6253 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) { 6254 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext()); 6255 llvm::Type *CoerceTy = 6256 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32); 6257 return ABIArgInfo::getDirect(CoerceTy); 6258 } 6259 6260 return getNaturalAlignIndirect(RetTy); 6261 } 6262 6263 /// isIllegalVector - check whether Ty is an illegal vector type. 6264 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const { 6265 if (const VectorType *VT = Ty->getAs<VectorType> ()) { 6266 // On targets that don't support FP16, FP16 is expanded into float, and we 6267 // don't want the ABI to depend on whether or not FP16 is supported in 6268 // hardware. Thus return false to coerce FP16 vectors into integer vectors. 6269 if (!getTarget().hasLegalHalfType() && 6270 (VT->getElementType()->isFloat16Type() || 6271 VT->getElementType()->isHalfType())) 6272 return true; 6273 if (isAndroid()) { 6274 // Android shipped using Clang 3.1, which supported a slightly different 6275 // vector ABI. The primary differences were that 3-element vector types 6276 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path 6277 // accepts that legacy behavior for Android only. 6278 // Check whether VT is legal. 6279 unsigned NumElements = VT->getNumElements(); 6280 // NumElements should be power of 2 or equal to 3. 6281 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3) 6282 return true; 6283 } else { 6284 // Check whether VT is legal. 6285 unsigned NumElements = VT->getNumElements(); 6286 uint64_t Size = getContext().getTypeSize(VT); 6287 // NumElements should be power of 2. 6288 if (!llvm::isPowerOf2_32(NumElements)) 6289 return true; 6290 // Size should be greater than 32 bits. 6291 return Size <= 32; 6292 } 6293 } 6294 return false; 6295 } 6296 6297 /// Return true if a type contains any 16-bit floating point vectors 6298 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const { 6299 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 6300 uint64_t NElements = AT->getSize().getZExtValue(); 6301 if (NElements == 0) 6302 return false; 6303 return containsAnyFP16Vectors(AT->getElementType()); 6304 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 6305 const RecordDecl *RD = RT->getDecl(); 6306 6307 // If this is a C++ record, check the bases first. 6308 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6309 if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) { 6310 return containsAnyFP16Vectors(B.getType()); 6311 })) 6312 return true; 6313 6314 if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) { 6315 return FD && containsAnyFP16Vectors(FD->getType()); 6316 })) 6317 return true; 6318 6319 return false; 6320 } else { 6321 if (const VectorType *VT = Ty->getAs<VectorType>()) 6322 return (VT->getElementType()->isFloat16Type() || 6323 VT->getElementType()->isHalfType()); 6324 return false; 6325 } 6326 } 6327 6328 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 6329 llvm::Type *eltTy, 6330 unsigned numElts) const { 6331 if (!llvm::isPowerOf2_32(numElts)) 6332 return false; 6333 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy); 6334 if (size > 64) 6335 return false; 6336 if (vectorSize.getQuantity() != 8 && 6337 (vectorSize.getQuantity() != 16 || numElts == 1)) 6338 return false; 6339 return true; 6340 } 6341 6342 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 6343 // Homogeneous aggregates for AAPCS-VFP must have base types of float, 6344 // double, or 64-bit or 128-bit vectors. 6345 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 6346 if (BT->getKind() == BuiltinType::Float || 6347 BT->getKind() == BuiltinType::Double || 6348 BT->getKind() == BuiltinType::LongDouble) 6349 return true; 6350 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 6351 unsigned VecSize = getContext().getTypeSize(VT); 6352 if (VecSize == 64 || VecSize == 128) 6353 return true; 6354 } 6355 return false; 6356 } 6357 6358 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 6359 uint64_t Members) const { 6360 return Members <= 4; 6361 } 6362 6363 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention, 6364 bool acceptHalf) const { 6365 // Give precedence to user-specified calling conventions. 6366 if (callConvention != llvm::CallingConv::C) 6367 return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP); 6368 else 6369 return (getABIKind() == AAPCS_VFP) || 6370 (acceptHalf && (getABIKind() == AAPCS16_VFP)); 6371 } 6372 6373 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6374 QualType Ty) const { 6375 CharUnits SlotSize = CharUnits::fromQuantity(4); 6376 6377 // Empty records are ignored for parameter passing purposes. 6378 if (isEmptyRecord(getContext(), Ty, true)) { 6379 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 6380 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 6381 return Addr; 6382 } 6383 6384 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 6385 CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty); 6386 6387 // Use indirect if size of the illegal vector is bigger than 16 bytes. 6388 bool IsIndirect = false; 6389 const Type *Base = nullptr; 6390 uint64_t Members = 0; 6391 if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) { 6392 IsIndirect = true; 6393 6394 // ARMv7k passes structs bigger than 16 bytes indirectly, in space 6395 // allocated by the caller. 6396 } else if (TySize > CharUnits::fromQuantity(16) && 6397 getABIKind() == ARMABIInfo::AAPCS16_VFP && 6398 !isHomogeneousAggregate(Ty, Base, Members)) { 6399 IsIndirect = true; 6400 6401 // Otherwise, bound the type's ABI alignment. 6402 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for 6403 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte. 6404 // Our callers should be prepared to handle an under-aligned address. 6405 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6406 getABIKind() == ARMABIInfo::AAPCS) { 6407 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 6408 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8)); 6409 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 6410 // ARMv7k allows type alignment up to 16 bytes. 6411 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 6412 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16)); 6413 } else { 6414 TyAlignForABI = CharUnits::fromQuantity(4); 6415 } 6416 6417 std::pair<CharUnits, CharUnits> TyInfo = { TySize, TyAlignForABI }; 6418 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo, 6419 SlotSize, /*AllowHigherAlign*/ true); 6420 } 6421 6422 //===----------------------------------------------------------------------===// 6423 // NVPTX ABI Implementation 6424 //===----------------------------------------------------------------------===// 6425 6426 namespace { 6427 6428 class NVPTXABIInfo : public ABIInfo { 6429 public: 6430 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 6431 6432 ABIArgInfo classifyReturnType(QualType RetTy) const; 6433 ABIArgInfo classifyArgumentType(QualType Ty) const; 6434 6435 void computeInfo(CGFunctionInfo &FI) const override; 6436 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6437 QualType Ty) const override; 6438 }; 6439 6440 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo { 6441 public: 6442 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT) 6443 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {} 6444 6445 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6446 CodeGen::CodeGenModule &M) const override; 6447 bool shouldEmitStaticExternCAliases() const override; 6448 6449 private: 6450 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the 6451 // resulting MDNode to the nvvm.annotations MDNode. 6452 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand); 6453 }; 6454 6455 /// Checks if the type is unsupported directly by the current target. 6456 static bool isUnsupportedType(ASTContext &Context, QualType T) { 6457 if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type()) 6458 return true; 6459 if (!Context.getTargetInfo().hasFloat128Type() && 6460 (T->isFloat128Type() || 6461 (T->isRealFloatingType() && Context.getTypeSize(T) == 128))) 6462 return true; 6463 if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() && 6464 Context.getTypeSize(T) > 64) 6465 return true; 6466 if (const auto *AT = T->getAsArrayTypeUnsafe()) 6467 return isUnsupportedType(Context, AT->getElementType()); 6468 const auto *RT = T->getAs<RecordType>(); 6469 if (!RT) 6470 return false; 6471 const RecordDecl *RD = RT->getDecl(); 6472 6473 // If this is a C++ record, check the bases first. 6474 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6475 for (const CXXBaseSpecifier &I : CXXRD->bases()) 6476 if (isUnsupportedType(Context, I.getType())) 6477 return true; 6478 6479 for (const FieldDecl *I : RD->fields()) 6480 if (isUnsupportedType(Context, I->getType())) 6481 return true; 6482 return false; 6483 } 6484 6485 /// Coerce the given type into an array with maximum allowed size of elements. 6486 static ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, ASTContext &Context, 6487 llvm::LLVMContext &LLVMContext, 6488 unsigned MaxSize) { 6489 // Alignment and Size are measured in bits. 6490 const uint64_t Size = Context.getTypeSize(Ty); 6491 const uint64_t Alignment = Context.getTypeAlign(Ty); 6492 const unsigned Div = std::min<unsigned>(MaxSize, Alignment); 6493 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Div); 6494 const uint64_t NumElements = (Size + Div - 1) / Div; 6495 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 6496 } 6497 6498 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const { 6499 if (RetTy->isVoidType()) 6500 return ABIArgInfo::getIgnore(); 6501 6502 if (getContext().getLangOpts().OpenMP && 6503 getContext().getLangOpts().OpenMPIsDevice && 6504 isUnsupportedType(getContext(), RetTy)) 6505 return coerceToIntArrayWithLimit(RetTy, getContext(), getVMContext(), 64); 6506 6507 // note: this is different from default ABI 6508 if (!RetTy->isScalarType()) 6509 return ABIArgInfo::getDirect(); 6510 6511 // Treat an enum type as its underlying type. 6512 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 6513 RetTy = EnumTy->getDecl()->getIntegerType(); 6514 6515 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 6516 : ABIArgInfo::getDirect()); 6517 } 6518 6519 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const { 6520 // Treat an enum type as its underlying type. 6521 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 6522 Ty = EnumTy->getDecl()->getIntegerType(); 6523 6524 // Return aggregates type as indirect by value 6525 if (isAggregateTypeForABI(Ty)) 6526 return getNaturalAlignIndirect(Ty, /* byval */ true); 6527 6528 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 6529 : ABIArgInfo::getDirect()); 6530 } 6531 6532 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const { 6533 if (!getCXXABI().classifyReturnType(FI)) 6534 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 6535 for (auto &I : FI.arguments()) 6536 I.info = classifyArgumentType(I.type); 6537 6538 // Always honor user-specified calling convention. 6539 if (FI.getCallingConvention() != llvm::CallingConv::C) 6540 return; 6541 6542 FI.setEffectiveCallingConvention(getRuntimeCC()); 6543 } 6544 6545 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6546 QualType Ty) const { 6547 llvm_unreachable("NVPTX does not support varargs"); 6548 } 6549 6550 void NVPTXTargetCodeGenInfo::setTargetAttributes( 6551 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 6552 if (GV->isDeclaration()) 6553 return; 6554 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 6555 if (!FD) return; 6556 6557 llvm::Function *F = cast<llvm::Function>(GV); 6558 6559 // Perform special handling in OpenCL mode 6560 if (M.getLangOpts().OpenCL) { 6561 // Use OpenCL function attributes to check for kernel functions 6562 // By default, all functions are device functions 6563 if (FD->hasAttr<OpenCLKernelAttr>()) { 6564 // OpenCL __kernel functions get kernel metadata 6565 // Create !{<func-ref>, metadata !"kernel", i32 1} node 6566 addNVVMMetadata(F, "kernel", 1); 6567 // And kernel functions are not subject to inlining 6568 F->addFnAttr(llvm::Attribute::NoInline); 6569 } 6570 } 6571 6572 // Perform special handling in CUDA mode. 6573 if (M.getLangOpts().CUDA) { 6574 // CUDA __global__ functions get a kernel metadata entry. Since 6575 // __global__ functions cannot be called from the device, we do not 6576 // need to set the noinline attribute. 6577 if (FD->hasAttr<CUDAGlobalAttr>()) { 6578 // Create !{<func-ref>, metadata !"kernel", i32 1} node 6579 addNVVMMetadata(F, "kernel", 1); 6580 } 6581 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) { 6582 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node 6583 llvm::APSInt MaxThreads(32); 6584 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext()); 6585 if (MaxThreads > 0) 6586 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue()); 6587 6588 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was 6589 // not specified in __launch_bounds__ or if the user specified a 0 value, 6590 // we don't have to add a PTX directive. 6591 if (Attr->getMinBlocks()) { 6592 llvm::APSInt MinBlocks(32); 6593 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext()); 6594 if (MinBlocks > 0) 6595 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node 6596 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue()); 6597 } 6598 } 6599 } 6600 } 6601 6602 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name, 6603 int Operand) { 6604 llvm::Module *M = F->getParent(); 6605 llvm::LLVMContext &Ctx = M->getContext(); 6606 6607 // Get "nvvm.annotations" metadata node 6608 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); 6609 6610 llvm::Metadata *MDVals[] = { 6611 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name), 6612 llvm::ConstantAsMetadata::get( 6613 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))}; 6614 // Append metadata to nvvm.annotations 6615 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 6616 } 6617 6618 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 6619 return false; 6620 } 6621 } 6622 6623 //===----------------------------------------------------------------------===// 6624 // SystemZ ABI Implementation 6625 //===----------------------------------------------------------------------===// 6626 6627 namespace { 6628 6629 class SystemZABIInfo : public SwiftABIInfo { 6630 bool HasVector; 6631 6632 public: 6633 SystemZABIInfo(CodeGenTypes &CGT, bool HV) 6634 : SwiftABIInfo(CGT), HasVector(HV) {} 6635 6636 bool isPromotableIntegerType(QualType Ty) const; 6637 bool isCompoundType(QualType Ty) const; 6638 bool isVectorArgumentType(QualType Ty) const; 6639 bool isFPArgumentType(QualType Ty) const; 6640 QualType GetSingleElementType(QualType Ty) const; 6641 6642 ABIArgInfo classifyReturnType(QualType RetTy) const; 6643 ABIArgInfo classifyArgumentType(QualType ArgTy) const; 6644 6645 void computeInfo(CGFunctionInfo &FI) const override { 6646 if (!getCXXABI().classifyReturnType(FI)) 6647 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 6648 for (auto &I : FI.arguments()) 6649 I.info = classifyArgumentType(I.type); 6650 } 6651 6652 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6653 QualType Ty) const override; 6654 6655 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 6656 bool asReturnValue) const override { 6657 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 6658 } 6659 bool isSwiftErrorInRegister() const override { 6660 return false; 6661 } 6662 }; 6663 6664 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo { 6665 public: 6666 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector) 6667 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {} 6668 }; 6669 6670 } 6671 6672 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const { 6673 // Treat an enum type as its underlying type. 6674 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 6675 Ty = EnumTy->getDecl()->getIntegerType(); 6676 6677 // Promotable integer types are required to be promoted by the ABI. 6678 if (Ty->isPromotableIntegerType()) 6679 return true; 6680 6681 // 32-bit values must also be promoted. 6682 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 6683 switch (BT->getKind()) { 6684 case BuiltinType::Int: 6685 case BuiltinType::UInt: 6686 return true; 6687 default: 6688 return false; 6689 } 6690 return false; 6691 } 6692 6693 bool SystemZABIInfo::isCompoundType(QualType Ty) const { 6694 return (Ty->isAnyComplexType() || 6695 Ty->isVectorType() || 6696 isAggregateTypeForABI(Ty)); 6697 } 6698 6699 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const { 6700 return (HasVector && 6701 Ty->isVectorType() && 6702 getContext().getTypeSize(Ty) <= 128); 6703 } 6704 6705 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const { 6706 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 6707 switch (BT->getKind()) { 6708 case BuiltinType::Float: 6709 case BuiltinType::Double: 6710 return true; 6711 default: 6712 return false; 6713 } 6714 6715 return false; 6716 } 6717 6718 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const { 6719 if (const RecordType *RT = Ty->getAsStructureType()) { 6720 const RecordDecl *RD = RT->getDecl(); 6721 QualType Found; 6722 6723 // If this is a C++ record, check the bases first. 6724 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6725 for (const auto &I : CXXRD->bases()) { 6726 QualType Base = I.getType(); 6727 6728 // Empty bases don't affect things either way. 6729 if (isEmptyRecord(getContext(), Base, true)) 6730 continue; 6731 6732 if (!Found.isNull()) 6733 return Ty; 6734 Found = GetSingleElementType(Base); 6735 } 6736 6737 // Check the fields. 6738 for (const auto *FD : RD->fields()) { 6739 // For compatibility with GCC, ignore empty bitfields in C++ mode. 6740 // Unlike isSingleElementStruct(), empty structure and array fields 6741 // do count. So do anonymous bitfields that aren't zero-sized. 6742 if (getContext().getLangOpts().CPlusPlus && 6743 FD->isZeroLengthBitField(getContext())) 6744 continue; 6745 6746 // Unlike isSingleElementStruct(), arrays do not count. 6747 // Nested structures still do though. 6748 if (!Found.isNull()) 6749 return Ty; 6750 Found = GetSingleElementType(FD->getType()); 6751 } 6752 6753 // Unlike isSingleElementStruct(), trailing padding is allowed. 6754 // An 8-byte aligned struct s { float f; } is passed as a double. 6755 if (!Found.isNull()) 6756 return Found; 6757 } 6758 6759 return Ty; 6760 } 6761 6762 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6763 QualType Ty) const { 6764 // Assume that va_list type is correct; should be pointer to LLVM type: 6765 // struct { 6766 // i64 __gpr; 6767 // i64 __fpr; 6768 // i8 *__overflow_arg_area; 6769 // i8 *__reg_save_area; 6770 // }; 6771 6772 // Every non-vector argument occupies 8 bytes and is passed by preference 6773 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are 6774 // always passed on the stack. 6775 Ty = getContext().getCanonicalType(Ty); 6776 auto TyInfo = getContext().getTypeInfoInChars(Ty); 6777 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty); 6778 llvm::Type *DirectTy = ArgTy; 6779 ABIArgInfo AI = classifyArgumentType(Ty); 6780 bool IsIndirect = AI.isIndirect(); 6781 bool InFPRs = false; 6782 bool IsVector = false; 6783 CharUnits UnpaddedSize; 6784 CharUnits DirectAlign; 6785 if (IsIndirect) { 6786 DirectTy = llvm::PointerType::getUnqual(DirectTy); 6787 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8); 6788 } else { 6789 if (AI.getCoerceToType()) 6790 ArgTy = AI.getCoerceToType(); 6791 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy(); 6792 IsVector = ArgTy->isVectorTy(); 6793 UnpaddedSize = TyInfo.first; 6794 DirectAlign = TyInfo.second; 6795 } 6796 CharUnits PaddedSize = CharUnits::fromQuantity(8); 6797 if (IsVector && UnpaddedSize > PaddedSize) 6798 PaddedSize = CharUnits::fromQuantity(16); 6799 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size."); 6800 6801 CharUnits Padding = (PaddedSize - UnpaddedSize); 6802 6803 llvm::Type *IndexTy = CGF.Int64Ty; 6804 llvm::Value *PaddedSizeV = 6805 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity()); 6806 6807 if (IsVector) { 6808 // Work out the address of a vector argument on the stack. 6809 // Vector arguments are always passed in the high bits of a 6810 // single (8 byte) or double (16 byte) stack slot. 6811 Address OverflowArgAreaPtr = 6812 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 6813 Address OverflowArgArea = 6814 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 6815 TyInfo.second); 6816 Address MemAddr = 6817 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr"); 6818 6819 // Update overflow_arg_area_ptr pointer 6820 llvm::Value *NewOverflowArgArea = 6821 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV, 6822 "overflow_arg_area"); 6823 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 6824 6825 return MemAddr; 6826 } 6827 6828 assert(PaddedSize.getQuantity() == 8); 6829 6830 unsigned MaxRegs, RegCountField, RegSaveIndex; 6831 CharUnits RegPadding; 6832 if (InFPRs) { 6833 MaxRegs = 4; // Maximum of 4 FPR arguments 6834 RegCountField = 1; // __fpr 6835 RegSaveIndex = 16; // save offset for f0 6836 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR 6837 } else { 6838 MaxRegs = 5; // Maximum of 5 GPR arguments 6839 RegCountField = 0; // __gpr 6840 RegSaveIndex = 2; // save offset for r2 6841 RegPadding = Padding; // values are passed in the low bits of a GPR 6842 } 6843 6844 Address RegCountPtr = 6845 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr"); 6846 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count"); 6847 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs); 6848 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV, 6849 "fits_in_regs"); 6850 6851 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 6852 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 6853 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 6854 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 6855 6856 // Emit code to load the value if it was passed in registers. 6857 CGF.EmitBlock(InRegBlock); 6858 6859 // Work out the address of an argument register. 6860 llvm::Value *ScaledRegCount = 6861 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count"); 6862 llvm::Value *RegBase = 6863 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity() 6864 + RegPadding.getQuantity()); 6865 llvm::Value *RegOffset = 6866 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset"); 6867 Address RegSaveAreaPtr = 6868 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr"); 6869 llvm::Value *RegSaveArea = 6870 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area"); 6871 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset, 6872 "raw_reg_addr"), 6873 PaddedSize); 6874 Address RegAddr = 6875 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr"); 6876 6877 // Update the register count 6878 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1); 6879 llvm::Value *NewRegCount = 6880 CGF.Builder.CreateAdd(RegCount, One, "reg_count"); 6881 CGF.Builder.CreateStore(NewRegCount, RegCountPtr); 6882 CGF.EmitBranch(ContBlock); 6883 6884 // Emit code to load the value if it was passed in memory. 6885 CGF.EmitBlock(InMemBlock); 6886 6887 // Work out the address of a stack argument. 6888 Address OverflowArgAreaPtr = 6889 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 6890 Address OverflowArgArea = 6891 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 6892 PaddedSize); 6893 Address RawMemAddr = 6894 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr"); 6895 Address MemAddr = 6896 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr"); 6897 6898 // Update overflow_arg_area_ptr pointer 6899 llvm::Value *NewOverflowArgArea = 6900 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV, 6901 "overflow_arg_area"); 6902 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 6903 CGF.EmitBranch(ContBlock); 6904 6905 // Return the appropriate result. 6906 CGF.EmitBlock(ContBlock); 6907 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 6908 MemAddr, InMemBlock, "va_arg.addr"); 6909 6910 if (IsIndirect) 6911 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"), 6912 TyInfo.second); 6913 6914 return ResAddr; 6915 } 6916 6917 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const { 6918 if (RetTy->isVoidType()) 6919 return ABIArgInfo::getIgnore(); 6920 if (isVectorArgumentType(RetTy)) 6921 return ABIArgInfo::getDirect(); 6922 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64) 6923 return getNaturalAlignIndirect(RetTy); 6924 return (isPromotableIntegerType(RetTy) ? ABIArgInfo::getExtend(RetTy) 6925 : ABIArgInfo::getDirect()); 6926 } 6927 6928 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const { 6929 // Handle the generic C++ ABI. 6930 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 6931 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 6932 6933 // Integers and enums are extended to full register width. 6934 if (isPromotableIntegerType(Ty)) 6935 return ABIArgInfo::getExtend(Ty); 6936 6937 // Handle vector types and vector-like structure types. Note that 6938 // as opposed to float-like structure types, we do not allow any 6939 // padding for vector-like structures, so verify the sizes match. 6940 uint64_t Size = getContext().getTypeSize(Ty); 6941 QualType SingleElementTy = GetSingleElementType(Ty); 6942 if (isVectorArgumentType(SingleElementTy) && 6943 getContext().getTypeSize(SingleElementTy) == Size) 6944 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy)); 6945 6946 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly. 6947 if (Size != 8 && Size != 16 && Size != 32 && Size != 64) 6948 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 6949 6950 // Handle small structures. 6951 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6952 // Structures with flexible arrays have variable length, so really 6953 // fail the size test above. 6954 const RecordDecl *RD = RT->getDecl(); 6955 if (RD->hasFlexibleArrayMember()) 6956 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 6957 6958 // The structure is passed as an unextended integer, a float, or a double. 6959 llvm::Type *PassTy; 6960 if (isFPArgumentType(SingleElementTy)) { 6961 assert(Size == 32 || Size == 64); 6962 if (Size == 32) 6963 PassTy = llvm::Type::getFloatTy(getVMContext()); 6964 else 6965 PassTy = llvm::Type::getDoubleTy(getVMContext()); 6966 } else 6967 PassTy = llvm::IntegerType::get(getVMContext(), Size); 6968 return ABIArgInfo::getDirect(PassTy); 6969 } 6970 6971 // Non-structure compounds are passed indirectly. 6972 if (isCompoundType(Ty)) 6973 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 6974 6975 return ABIArgInfo::getDirect(nullptr); 6976 } 6977 6978 //===----------------------------------------------------------------------===// 6979 // MSP430 ABI Implementation 6980 //===----------------------------------------------------------------------===// 6981 6982 namespace { 6983 6984 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { 6985 public: 6986 MSP430TargetCodeGenInfo(CodeGenTypes &CGT) 6987 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 6988 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6989 CodeGen::CodeGenModule &M) const override; 6990 }; 6991 6992 } 6993 6994 void MSP430TargetCodeGenInfo::setTargetAttributes( 6995 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 6996 if (GV->isDeclaration()) 6997 return; 6998 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 6999 const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>(); 7000 if (!InterruptAttr) 7001 return; 7002 7003 // Handle 'interrupt' attribute: 7004 llvm::Function *F = cast<llvm::Function>(GV); 7005 7006 // Step 1: Set ISR calling convention. 7007 F->setCallingConv(llvm::CallingConv::MSP430_INTR); 7008 7009 // Step 2: Add attributes goodness. 7010 F->addFnAttr(llvm::Attribute::NoInline); 7011 F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber())); 7012 } 7013 } 7014 7015 //===----------------------------------------------------------------------===// 7016 // MIPS ABI Implementation. This works for both little-endian and 7017 // big-endian variants. 7018 //===----------------------------------------------------------------------===// 7019 7020 namespace { 7021 class MipsABIInfo : public ABIInfo { 7022 bool IsO32; 7023 unsigned MinABIStackAlignInBytes, StackAlignInBytes; 7024 void CoerceToIntArgs(uint64_t TySize, 7025 SmallVectorImpl<llvm::Type *> &ArgList) const; 7026 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const; 7027 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; 7028 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; 7029 public: 7030 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : 7031 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8), 7032 StackAlignInBytes(IsO32 ? 8 : 16) {} 7033 7034 ABIArgInfo classifyReturnType(QualType RetTy) const; 7035 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; 7036 void computeInfo(CGFunctionInfo &FI) const override; 7037 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7038 QualType Ty) const override; 7039 ABIArgInfo extendType(QualType Ty) const; 7040 }; 7041 7042 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { 7043 unsigned SizeOfUnwindException; 7044 public: 7045 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) 7046 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)), 7047 SizeOfUnwindException(IsO32 ? 24 : 32) {} 7048 7049 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 7050 return 29; 7051 } 7052 7053 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7054 CodeGen::CodeGenModule &CGM) const override { 7055 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7056 if (!FD) return; 7057 llvm::Function *Fn = cast<llvm::Function>(GV); 7058 7059 if (FD->hasAttr<MipsLongCallAttr>()) 7060 Fn->addFnAttr("long-call"); 7061 else if (FD->hasAttr<MipsShortCallAttr>()) 7062 Fn->addFnAttr("short-call"); 7063 7064 // Other attributes do not have a meaning for declarations. 7065 if (GV->isDeclaration()) 7066 return; 7067 7068 if (FD->hasAttr<Mips16Attr>()) { 7069 Fn->addFnAttr("mips16"); 7070 } 7071 else if (FD->hasAttr<NoMips16Attr>()) { 7072 Fn->addFnAttr("nomips16"); 7073 } 7074 7075 if (FD->hasAttr<MicroMipsAttr>()) 7076 Fn->addFnAttr("micromips"); 7077 else if (FD->hasAttr<NoMicroMipsAttr>()) 7078 Fn->addFnAttr("nomicromips"); 7079 7080 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>(); 7081 if (!Attr) 7082 return; 7083 7084 const char *Kind; 7085 switch (Attr->getInterrupt()) { 7086 case MipsInterruptAttr::eic: Kind = "eic"; break; 7087 case MipsInterruptAttr::sw0: Kind = "sw0"; break; 7088 case MipsInterruptAttr::sw1: Kind = "sw1"; break; 7089 case MipsInterruptAttr::hw0: Kind = "hw0"; break; 7090 case MipsInterruptAttr::hw1: Kind = "hw1"; break; 7091 case MipsInterruptAttr::hw2: Kind = "hw2"; break; 7092 case MipsInterruptAttr::hw3: Kind = "hw3"; break; 7093 case MipsInterruptAttr::hw4: Kind = "hw4"; break; 7094 case MipsInterruptAttr::hw5: Kind = "hw5"; break; 7095 } 7096 7097 Fn->addFnAttr("interrupt", Kind); 7098 7099 } 7100 7101 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 7102 llvm::Value *Address) const override; 7103 7104 unsigned getSizeOfUnwindException() const override { 7105 return SizeOfUnwindException; 7106 } 7107 }; 7108 } 7109 7110 void MipsABIInfo::CoerceToIntArgs( 7111 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const { 7112 llvm::IntegerType *IntTy = 7113 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 7114 7115 // Add (TySize / MinABIStackAlignInBytes) args of IntTy. 7116 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N) 7117 ArgList.push_back(IntTy); 7118 7119 // If necessary, add one more integer type to ArgList. 7120 unsigned R = TySize % (MinABIStackAlignInBytes * 8); 7121 7122 if (R) 7123 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); 7124 } 7125 7126 // In N32/64, an aligned double precision floating point field is passed in 7127 // a register. 7128 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const { 7129 SmallVector<llvm::Type*, 8> ArgList, IntArgList; 7130 7131 if (IsO32) { 7132 CoerceToIntArgs(TySize, ArgList); 7133 return llvm::StructType::get(getVMContext(), ArgList); 7134 } 7135 7136 if (Ty->isComplexType()) 7137 return CGT.ConvertType(Ty); 7138 7139 const RecordType *RT = Ty->getAs<RecordType>(); 7140 7141 // Unions/vectors are passed in integer registers. 7142 if (!RT || !RT->isStructureOrClassType()) { 7143 CoerceToIntArgs(TySize, ArgList); 7144 return llvm::StructType::get(getVMContext(), ArgList); 7145 } 7146 7147 const RecordDecl *RD = RT->getDecl(); 7148 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7149 assert(!(TySize % 8) && "Size of structure must be multiple of 8."); 7150 7151 uint64_t LastOffset = 0; 7152 unsigned idx = 0; 7153 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); 7154 7155 // Iterate over fields in the struct/class and check if there are any aligned 7156 // double fields. 7157 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 7158 i != e; ++i, ++idx) { 7159 const QualType Ty = i->getType(); 7160 const BuiltinType *BT = Ty->getAs<BuiltinType>(); 7161 7162 if (!BT || BT->getKind() != BuiltinType::Double) 7163 continue; 7164 7165 uint64_t Offset = Layout.getFieldOffset(idx); 7166 if (Offset % 64) // Ignore doubles that are not aligned. 7167 continue; 7168 7169 // Add ((Offset - LastOffset) / 64) args of type i64. 7170 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) 7171 ArgList.push_back(I64); 7172 7173 // Add double type. 7174 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); 7175 LastOffset = Offset + 64; 7176 } 7177 7178 CoerceToIntArgs(TySize - LastOffset, IntArgList); 7179 ArgList.append(IntArgList.begin(), IntArgList.end()); 7180 7181 return llvm::StructType::get(getVMContext(), ArgList); 7182 } 7183 7184 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset, 7185 uint64_t Offset) const { 7186 if (OrigOffset + MinABIStackAlignInBytes > Offset) 7187 return nullptr; 7188 7189 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8); 7190 } 7191 7192 ABIArgInfo 7193 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { 7194 Ty = useFirstFieldIfTransparentUnion(Ty); 7195 7196 uint64_t OrigOffset = Offset; 7197 uint64_t TySize = getContext().getTypeSize(Ty); 7198 uint64_t Align = getContext().getTypeAlign(Ty) / 8; 7199 7200 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes), 7201 (uint64_t)StackAlignInBytes); 7202 unsigned CurrOffset = llvm::alignTo(Offset, Align); 7203 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8; 7204 7205 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) { 7206 // Ignore empty aggregates. 7207 if (TySize == 0) 7208 return ABIArgInfo::getIgnore(); 7209 7210 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 7211 Offset = OrigOffset + MinABIStackAlignInBytes; 7212 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7213 } 7214 7215 // If we have reached here, aggregates are passed directly by coercing to 7216 // another structure type. Padding is inserted if the offset of the 7217 // aggregate is unaligned. 7218 ABIArgInfo ArgInfo = 7219 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0, 7220 getPaddingType(OrigOffset, CurrOffset)); 7221 ArgInfo.setInReg(true); 7222 return ArgInfo; 7223 } 7224 7225 // Treat an enum type as its underlying type. 7226 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7227 Ty = EnumTy->getDecl()->getIntegerType(); 7228 7229 // All integral types are promoted to the GPR width. 7230 if (Ty->isIntegralOrEnumerationType()) 7231 return extendType(Ty); 7232 7233 return ABIArgInfo::getDirect( 7234 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset)); 7235 } 7236 7237 llvm::Type* 7238 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { 7239 const RecordType *RT = RetTy->getAs<RecordType>(); 7240 SmallVector<llvm::Type*, 8> RTList; 7241 7242 if (RT && RT->isStructureOrClassType()) { 7243 const RecordDecl *RD = RT->getDecl(); 7244 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7245 unsigned FieldCnt = Layout.getFieldCount(); 7246 7247 // N32/64 returns struct/classes in floating point registers if the 7248 // following conditions are met: 7249 // 1. The size of the struct/class is no larger than 128-bit. 7250 // 2. The struct/class has one or two fields all of which are floating 7251 // point types. 7252 // 3. The offset of the first field is zero (this follows what gcc does). 7253 // 7254 // Any other composite results are returned in integer registers. 7255 // 7256 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { 7257 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); 7258 for (; b != e; ++b) { 7259 const BuiltinType *BT = b->getType()->getAs<BuiltinType>(); 7260 7261 if (!BT || !BT->isFloatingPoint()) 7262 break; 7263 7264 RTList.push_back(CGT.ConvertType(b->getType())); 7265 } 7266 7267 if (b == e) 7268 return llvm::StructType::get(getVMContext(), RTList, 7269 RD->hasAttr<PackedAttr>()); 7270 7271 RTList.clear(); 7272 } 7273 } 7274 7275 CoerceToIntArgs(Size, RTList); 7276 return llvm::StructType::get(getVMContext(), RTList); 7277 } 7278 7279 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { 7280 uint64_t Size = getContext().getTypeSize(RetTy); 7281 7282 if (RetTy->isVoidType()) 7283 return ABIArgInfo::getIgnore(); 7284 7285 // O32 doesn't treat zero-sized structs differently from other structs. 7286 // However, N32/N64 ignores zero sized return values. 7287 if (!IsO32 && Size == 0) 7288 return ABIArgInfo::getIgnore(); 7289 7290 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) { 7291 if (Size <= 128) { 7292 if (RetTy->isAnyComplexType()) 7293 return ABIArgInfo::getDirect(); 7294 7295 // O32 returns integer vectors in registers and N32/N64 returns all small 7296 // aggregates in registers. 7297 if (!IsO32 || 7298 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) { 7299 ABIArgInfo ArgInfo = 7300 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 7301 ArgInfo.setInReg(true); 7302 return ArgInfo; 7303 } 7304 } 7305 7306 return getNaturalAlignIndirect(RetTy); 7307 } 7308 7309 // Treat an enum type as its underlying type. 7310 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7311 RetTy = EnumTy->getDecl()->getIntegerType(); 7312 7313 if (RetTy->isPromotableIntegerType()) 7314 return ABIArgInfo::getExtend(RetTy); 7315 7316 if ((RetTy->isUnsignedIntegerOrEnumerationType() || 7317 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32) 7318 return ABIArgInfo::getSignExtend(RetTy); 7319 7320 return ABIArgInfo::getDirect(); 7321 } 7322 7323 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { 7324 ABIArgInfo &RetInfo = FI.getReturnInfo(); 7325 if (!getCXXABI().classifyReturnType(FI)) 7326 RetInfo = classifyReturnType(FI.getReturnType()); 7327 7328 // Check if a pointer to an aggregate is passed as a hidden argument. 7329 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0; 7330 7331 for (auto &I : FI.arguments()) 7332 I.info = classifyArgumentType(I.type, Offset); 7333 } 7334 7335 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7336 QualType OrigTy) const { 7337 QualType Ty = OrigTy; 7338 7339 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64. 7340 // Pointers are also promoted in the same way but this only matters for N32. 7341 unsigned SlotSizeInBits = IsO32 ? 32 : 64; 7342 unsigned PtrWidth = getTarget().getPointerWidth(0); 7343 bool DidPromote = false; 7344 if ((Ty->isIntegerType() && 7345 getContext().getIntWidth(Ty) < SlotSizeInBits) || 7346 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) { 7347 DidPromote = true; 7348 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits, 7349 Ty->isSignedIntegerType()); 7350 } 7351 7352 auto TyInfo = getContext().getTypeInfoInChars(Ty); 7353 7354 // The alignment of things in the argument area is never larger than 7355 // StackAlignInBytes. 7356 TyInfo.second = 7357 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes)); 7358 7359 // MinABIStackAlignInBytes is the size of argument slots on the stack. 7360 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes); 7361 7362 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 7363 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true); 7364 7365 7366 // If there was a promotion, "unpromote" into a temporary. 7367 // TODO: can we just use a pointer into a subset of the original slot? 7368 if (DidPromote) { 7369 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp"); 7370 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr); 7371 7372 // Truncate down to the right width. 7373 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType() 7374 : CGF.IntPtrTy); 7375 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy); 7376 if (OrigTy->isPointerType()) 7377 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType()); 7378 7379 CGF.Builder.CreateStore(V, Temp); 7380 Addr = Temp; 7381 } 7382 7383 return Addr; 7384 } 7385 7386 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const { 7387 int TySize = getContext().getTypeSize(Ty); 7388 7389 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended. 7390 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 7391 return ABIArgInfo::getSignExtend(Ty); 7392 7393 return ABIArgInfo::getExtend(Ty); 7394 } 7395 7396 bool 7397 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 7398 llvm::Value *Address) const { 7399 // This information comes from gcc's implementation, which seems to 7400 // as canonical as it gets. 7401 7402 // Everything on MIPS is 4 bytes. Double-precision FP registers 7403 // are aliased to pairs of single-precision FP registers. 7404 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 7405 7406 // 0-31 are the general purpose registers, $0 - $31. 7407 // 32-63 are the floating-point registers, $f0 - $f31. 7408 // 64 and 65 are the multiply/divide registers, $hi and $lo. 7409 // 66 is the (notional, I think) register for signal-handler return. 7410 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); 7411 7412 // 67-74 are the floating-point status registers, $fcc0 - $fcc7. 7413 // They are one bit wide and ignored here. 7414 7415 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. 7416 // (coprocessor 1 is the FP unit) 7417 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. 7418 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. 7419 // 176-181 are the DSP accumulator registers. 7420 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); 7421 return false; 7422 } 7423 7424 //===----------------------------------------------------------------------===// 7425 // AVR ABI Implementation. 7426 //===----------------------------------------------------------------------===// 7427 7428 namespace { 7429 class AVRTargetCodeGenInfo : public TargetCodeGenInfo { 7430 public: 7431 AVRTargetCodeGenInfo(CodeGenTypes &CGT) 7432 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { } 7433 7434 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7435 CodeGen::CodeGenModule &CGM) const override { 7436 if (GV->isDeclaration()) 7437 return; 7438 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 7439 if (!FD) return; 7440 auto *Fn = cast<llvm::Function>(GV); 7441 7442 if (FD->getAttr<AVRInterruptAttr>()) 7443 Fn->addFnAttr("interrupt"); 7444 7445 if (FD->getAttr<AVRSignalAttr>()) 7446 Fn->addFnAttr("signal"); 7447 } 7448 }; 7449 } 7450 7451 //===----------------------------------------------------------------------===// 7452 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. 7453 // Currently subclassed only to implement custom OpenCL C function attribute 7454 // handling. 7455 //===----------------------------------------------------------------------===// 7456 7457 namespace { 7458 7459 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { 7460 public: 7461 TCETargetCodeGenInfo(CodeGenTypes &CGT) 7462 : DefaultTargetCodeGenInfo(CGT) {} 7463 7464 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7465 CodeGen::CodeGenModule &M) const override; 7466 }; 7467 7468 void TCETargetCodeGenInfo::setTargetAttributes( 7469 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7470 if (GV->isDeclaration()) 7471 return; 7472 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7473 if (!FD) return; 7474 7475 llvm::Function *F = cast<llvm::Function>(GV); 7476 7477 if (M.getLangOpts().OpenCL) { 7478 if (FD->hasAttr<OpenCLKernelAttr>()) { 7479 // OpenCL C Kernel functions are not subject to inlining 7480 F->addFnAttr(llvm::Attribute::NoInline); 7481 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>(); 7482 if (Attr) { 7483 // Convert the reqd_work_group_size() attributes to metadata. 7484 llvm::LLVMContext &Context = F->getContext(); 7485 llvm::NamedMDNode *OpenCLMetadata = 7486 M.getModule().getOrInsertNamedMetadata( 7487 "opencl.kernel_wg_size_info"); 7488 7489 SmallVector<llvm::Metadata *, 5> Operands; 7490 Operands.push_back(llvm::ConstantAsMetadata::get(F)); 7491 7492 Operands.push_back( 7493 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 7494 M.Int32Ty, llvm::APInt(32, Attr->getXDim())))); 7495 Operands.push_back( 7496 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 7497 M.Int32Ty, llvm::APInt(32, Attr->getYDim())))); 7498 Operands.push_back( 7499 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 7500 M.Int32Ty, llvm::APInt(32, Attr->getZDim())))); 7501 7502 // Add a boolean constant operand for "required" (true) or "hint" 7503 // (false) for implementing the work_group_size_hint attr later. 7504 // Currently always true as the hint is not yet implemented. 7505 Operands.push_back( 7506 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context))); 7507 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); 7508 } 7509 } 7510 } 7511 } 7512 7513 } 7514 7515 //===----------------------------------------------------------------------===// 7516 // Hexagon ABI Implementation 7517 //===----------------------------------------------------------------------===// 7518 7519 namespace { 7520 7521 class HexagonABIInfo : public ABIInfo { 7522 7523 7524 public: 7525 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 7526 7527 private: 7528 7529 ABIArgInfo classifyReturnType(QualType RetTy) const; 7530 ABIArgInfo classifyArgumentType(QualType RetTy) const; 7531 7532 void computeInfo(CGFunctionInfo &FI) const override; 7533 7534 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7535 QualType Ty) const override; 7536 }; 7537 7538 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { 7539 public: 7540 HexagonTargetCodeGenInfo(CodeGenTypes &CGT) 7541 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {} 7542 7543 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 7544 return 29; 7545 } 7546 }; 7547 7548 } 7549 7550 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { 7551 if (!getCXXABI().classifyReturnType(FI)) 7552 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7553 for (auto &I : FI.arguments()) 7554 I.info = classifyArgumentType(I.type); 7555 } 7556 7557 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const { 7558 if (!isAggregateTypeForABI(Ty)) { 7559 // Treat an enum type as its underlying type. 7560 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7561 Ty = EnumTy->getDecl()->getIntegerType(); 7562 7563 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 7564 : ABIArgInfo::getDirect()); 7565 } 7566 7567 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 7568 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7569 7570 // Ignore empty records. 7571 if (isEmptyRecord(getContext(), Ty, true)) 7572 return ABIArgInfo::getIgnore(); 7573 7574 uint64_t Size = getContext().getTypeSize(Ty); 7575 if (Size > 64) 7576 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 7577 // Pass in the smallest viable integer type. 7578 else if (Size > 32) 7579 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext())); 7580 else if (Size > 16) 7581 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 7582 else if (Size > 8) 7583 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 7584 else 7585 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 7586 } 7587 7588 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { 7589 if (RetTy->isVoidType()) 7590 return ABIArgInfo::getIgnore(); 7591 7592 // Large vector types should be returned via memory. 7593 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64) 7594 return getNaturalAlignIndirect(RetTy); 7595 7596 if (!isAggregateTypeForABI(RetTy)) { 7597 // Treat an enum type as its underlying type. 7598 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7599 RetTy = EnumTy->getDecl()->getIntegerType(); 7600 7601 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 7602 : ABIArgInfo::getDirect()); 7603 } 7604 7605 if (isEmptyRecord(getContext(), RetTy, true)) 7606 return ABIArgInfo::getIgnore(); 7607 7608 // Aggregates <= 8 bytes are returned in r0; other aggregates 7609 // are returned indirectly. 7610 uint64_t Size = getContext().getTypeSize(RetTy); 7611 if (Size <= 64) { 7612 // Return in the smallest viable integer type. 7613 if (Size <= 8) 7614 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 7615 if (Size <= 16) 7616 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 7617 if (Size <= 32) 7618 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 7619 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext())); 7620 } 7621 7622 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true); 7623 } 7624 7625 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7626 QualType Ty) const { 7627 // FIXME: Someone needs to audit that this handle alignment correctly. 7628 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 7629 getContext().getTypeInfoInChars(Ty), 7630 CharUnits::fromQuantity(4), 7631 /*AllowHigherAlign*/ true); 7632 } 7633 7634 //===----------------------------------------------------------------------===// 7635 // Lanai ABI Implementation 7636 //===----------------------------------------------------------------------===// 7637 7638 namespace { 7639 class LanaiABIInfo : public DefaultABIInfo { 7640 public: 7641 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 7642 7643 bool shouldUseInReg(QualType Ty, CCState &State) const; 7644 7645 void computeInfo(CGFunctionInfo &FI) const override { 7646 CCState State(FI); 7647 // Lanai uses 4 registers to pass arguments unless the function has the 7648 // regparm attribute set. 7649 if (FI.getHasRegParm()) { 7650 State.FreeRegs = FI.getRegParm(); 7651 } else { 7652 State.FreeRegs = 4; 7653 } 7654 7655 if (!getCXXABI().classifyReturnType(FI)) 7656 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7657 for (auto &I : FI.arguments()) 7658 I.info = classifyArgumentType(I.type, State); 7659 } 7660 7661 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 7662 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 7663 }; 7664 } // end anonymous namespace 7665 7666 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const { 7667 unsigned Size = getContext().getTypeSize(Ty); 7668 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U; 7669 7670 if (SizeInRegs == 0) 7671 return false; 7672 7673 if (SizeInRegs > State.FreeRegs) { 7674 State.FreeRegs = 0; 7675 return false; 7676 } 7677 7678 State.FreeRegs -= SizeInRegs; 7679 7680 return true; 7681 } 7682 7683 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal, 7684 CCState &State) const { 7685 if (!ByVal) { 7686 if (State.FreeRegs) { 7687 --State.FreeRegs; // Non-byval indirects just use one pointer. 7688 return getNaturalAlignIndirectInReg(Ty); 7689 } 7690 return getNaturalAlignIndirect(Ty, false); 7691 } 7692 7693 // Compute the byval alignment. 7694 const unsigned MinABIStackAlignInBytes = 4; 7695 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 7696 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 7697 /*Realign=*/TypeAlign > 7698 MinABIStackAlignInBytes); 7699 } 7700 7701 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty, 7702 CCState &State) const { 7703 // Check with the C++ ABI first. 7704 const RecordType *RT = Ty->getAs<RecordType>(); 7705 if (RT) { 7706 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 7707 if (RAA == CGCXXABI::RAA_Indirect) { 7708 return getIndirectResult(Ty, /*ByVal=*/false, State); 7709 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 7710 return getNaturalAlignIndirect(Ty, /*ByRef=*/true); 7711 } 7712 } 7713 7714 if (isAggregateTypeForABI(Ty)) { 7715 // Structures with flexible arrays are always indirect. 7716 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 7717 return getIndirectResult(Ty, /*ByVal=*/true, State); 7718 7719 // Ignore empty structs/unions. 7720 if (isEmptyRecord(getContext(), Ty, true)) 7721 return ABIArgInfo::getIgnore(); 7722 7723 llvm::LLVMContext &LLVMContext = getVMContext(); 7724 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 7725 if (SizeInRegs <= State.FreeRegs) { 7726 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 7727 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 7728 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 7729 State.FreeRegs -= SizeInRegs; 7730 return ABIArgInfo::getDirectInReg(Result); 7731 } else { 7732 State.FreeRegs = 0; 7733 } 7734 return getIndirectResult(Ty, true, State); 7735 } 7736 7737 // Treat an enum type as its underlying type. 7738 if (const auto *EnumTy = Ty->getAs<EnumType>()) 7739 Ty = EnumTy->getDecl()->getIntegerType(); 7740 7741 bool InReg = shouldUseInReg(Ty, State); 7742 if (Ty->isPromotableIntegerType()) { 7743 if (InReg) 7744 return ABIArgInfo::getDirectInReg(); 7745 return ABIArgInfo::getExtend(Ty); 7746 } 7747 if (InReg) 7748 return ABIArgInfo::getDirectInReg(); 7749 return ABIArgInfo::getDirect(); 7750 } 7751 7752 namespace { 7753 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo { 7754 public: 7755 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 7756 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {} 7757 }; 7758 } 7759 7760 //===----------------------------------------------------------------------===// 7761 // AMDGPU ABI Implementation 7762 //===----------------------------------------------------------------------===// 7763 7764 namespace { 7765 7766 class AMDGPUABIInfo final : public DefaultABIInfo { 7767 private: 7768 static const unsigned MaxNumRegsForArgsRet = 16; 7769 7770 unsigned numRegsForType(QualType Ty) const; 7771 7772 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 7773 bool isHomogeneousAggregateSmallEnough(const Type *Base, 7774 uint64_t Members) const override; 7775 7776 // Coerce HIP pointer arguments from generic pointers to global ones. 7777 llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS, 7778 unsigned ToAS) const { 7779 // Structure types. 7780 if (auto STy = dyn_cast<llvm::StructType>(Ty)) { 7781 SmallVector<llvm::Type *, 8> EltTys; 7782 bool Changed = false; 7783 for (auto T : STy->elements()) { 7784 auto NT = coerceKernelArgumentType(T, FromAS, ToAS); 7785 EltTys.push_back(NT); 7786 Changed |= (NT != T); 7787 } 7788 // Skip if there is no change in element types. 7789 if (!Changed) 7790 return STy; 7791 if (STy->hasName()) 7792 return llvm::StructType::create( 7793 EltTys, (STy->getName() + ".coerce").str(), STy->isPacked()); 7794 return llvm::StructType::get(getVMContext(), EltTys, STy->isPacked()); 7795 } 7796 // Arrary types. 7797 if (auto ATy = dyn_cast<llvm::ArrayType>(Ty)) { 7798 auto T = ATy->getElementType(); 7799 auto NT = coerceKernelArgumentType(T, FromAS, ToAS); 7800 // Skip if there is no change in that element type. 7801 if (NT == T) 7802 return ATy; 7803 return llvm::ArrayType::get(NT, ATy->getNumElements()); 7804 } 7805 // Single value types. 7806 if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS) 7807 return llvm::PointerType::get( 7808 cast<llvm::PointerType>(Ty)->getElementType(), ToAS); 7809 return Ty; 7810 } 7811 7812 public: 7813 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : 7814 DefaultABIInfo(CGT) {} 7815 7816 ABIArgInfo classifyReturnType(QualType RetTy) const; 7817 ABIArgInfo classifyKernelArgumentType(QualType Ty) const; 7818 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const; 7819 7820 void computeInfo(CGFunctionInfo &FI) const override; 7821 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7822 QualType Ty) const override; 7823 }; 7824 7825 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 7826 return true; 7827 } 7828 7829 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough( 7830 const Type *Base, uint64_t Members) const { 7831 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32; 7832 7833 // Homogeneous Aggregates may occupy at most 16 registers. 7834 return Members * NumRegs <= MaxNumRegsForArgsRet; 7835 } 7836 7837 /// Estimate number of registers the type will use when passed in registers. 7838 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const { 7839 unsigned NumRegs = 0; 7840 7841 if (const VectorType *VT = Ty->getAs<VectorType>()) { 7842 // Compute from the number of elements. The reported size is based on the 7843 // in-memory size, which includes the padding 4th element for 3-vectors. 7844 QualType EltTy = VT->getElementType(); 7845 unsigned EltSize = getContext().getTypeSize(EltTy); 7846 7847 // 16-bit element vectors should be passed as packed. 7848 if (EltSize == 16) 7849 return (VT->getNumElements() + 1) / 2; 7850 7851 unsigned EltNumRegs = (EltSize + 31) / 32; 7852 return EltNumRegs * VT->getNumElements(); 7853 } 7854 7855 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7856 const RecordDecl *RD = RT->getDecl(); 7857 assert(!RD->hasFlexibleArrayMember()); 7858 7859 for (const FieldDecl *Field : RD->fields()) { 7860 QualType FieldTy = Field->getType(); 7861 NumRegs += numRegsForType(FieldTy); 7862 } 7863 7864 return NumRegs; 7865 } 7866 7867 return (getContext().getTypeSize(Ty) + 31) / 32; 7868 } 7869 7870 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const { 7871 llvm::CallingConv::ID CC = FI.getCallingConvention(); 7872 7873 if (!getCXXABI().classifyReturnType(FI)) 7874 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7875 7876 unsigned NumRegsLeft = MaxNumRegsForArgsRet; 7877 for (auto &Arg : FI.arguments()) { 7878 if (CC == llvm::CallingConv::AMDGPU_KERNEL) { 7879 Arg.info = classifyKernelArgumentType(Arg.type); 7880 } else { 7881 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft); 7882 } 7883 } 7884 } 7885 7886 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7887 QualType Ty) const { 7888 llvm_unreachable("AMDGPU does not support varargs"); 7889 } 7890 7891 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const { 7892 if (isAggregateTypeForABI(RetTy)) { 7893 // Records with non-trivial destructors/copy-constructors should not be 7894 // returned by value. 7895 if (!getRecordArgABI(RetTy, getCXXABI())) { 7896 // Ignore empty structs/unions. 7897 if (isEmptyRecord(getContext(), RetTy, true)) 7898 return ABIArgInfo::getIgnore(); 7899 7900 // Lower single-element structs to just return a regular value. 7901 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 7902 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 7903 7904 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 7905 const RecordDecl *RD = RT->getDecl(); 7906 if (RD->hasFlexibleArrayMember()) 7907 return DefaultABIInfo::classifyReturnType(RetTy); 7908 } 7909 7910 // Pack aggregates <= 4 bytes into single VGPR or pair. 7911 uint64_t Size = getContext().getTypeSize(RetTy); 7912 if (Size <= 16) 7913 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 7914 7915 if (Size <= 32) 7916 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 7917 7918 if (Size <= 64) { 7919 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 7920 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 7921 } 7922 7923 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet) 7924 return ABIArgInfo::getDirect(); 7925 } 7926 } 7927 7928 // Otherwise just do the default thing. 7929 return DefaultABIInfo::classifyReturnType(RetTy); 7930 } 7931 7932 /// For kernels all parameters are really passed in a special buffer. It doesn't 7933 /// make sense to pass anything byval, so everything must be direct. 7934 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const { 7935 Ty = useFirstFieldIfTransparentUnion(Ty); 7936 7937 // TODO: Can we omit empty structs? 7938 7939 llvm::Type *LTy = nullptr; 7940 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 7941 LTy = CGT.ConvertType(QualType(SeltTy, 0)); 7942 7943 if (getContext().getLangOpts().HIP) { 7944 if (!LTy) 7945 LTy = CGT.ConvertType(Ty); 7946 LTy = coerceKernelArgumentType( 7947 LTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default), 7948 /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device)); 7949 } 7950 7951 // If we set CanBeFlattened to true, CodeGen will expand the struct to its 7952 // individual elements, which confuses the Clover OpenCL backend; therefore we 7953 // have to set it to false here. Other args of getDirect() are just defaults. 7954 return ABIArgInfo::getDirect(LTy, 0, nullptr, false); 7955 } 7956 7957 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty, 7958 unsigned &NumRegsLeft) const { 7959 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow"); 7960 7961 Ty = useFirstFieldIfTransparentUnion(Ty); 7962 7963 if (isAggregateTypeForABI(Ty)) { 7964 // Records with non-trivial destructors/copy-constructors should not be 7965 // passed by value. 7966 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 7967 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7968 7969 // Ignore empty structs/unions. 7970 if (isEmptyRecord(getContext(), Ty, true)) 7971 return ABIArgInfo::getIgnore(); 7972 7973 // Lower single-element structs to just pass a regular value. TODO: We 7974 // could do reasonable-size multiple-element structs too, using getExpand(), 7975 // though watch out for things like bitfields. 7976 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 7977 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 7978 7979 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7980 const RecordDecl *RD = RT->getDecl(); 7981 if (RD->hasFlexibleArrayMember()) 7982 return DefaultABIInfo::classifyArgumentType(Ty); 7983 } 7984 7985 // Pack aggregates <= 8 bytes into single VGPR or pair. 7986 uint64_t Size = getContext().getTypeSize(Ty); 7987 if (Size <= 64) { 7988 unsigned NumRegs = (Size + 31) / 32; 7989 NumRegsLeft -= std::min(NumRegsLeft, NumRegs); 7990 7991 if (Size <= 16) 7992 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 7993 7994 if (Size <= 32) 7995 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 7996 7997 // XXX: Should this be i64 instead, and should the limit increase? 7998 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 7999 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 8000 } 8001 8002 if (NumRegsLeft > 0) { 8003 unsigned NumRegs = numRegsForType(Ty); 8004 if (NumRegsLeft >= NumRegs) { 8005 NumRegsLeft -= NumRegs; 8006 return ABIArgInfo::getDirect(); 8007 } 8008 } 8009 } 8010 8011 // Otherwise just do the default thing. 8012 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty); 8013 if (!ArgInfo.isIndirect()) { 8014 unsigned NumRegs = numRegsForType(Ty); 8015 NumRegsLeft -= std::min(NumRegs, NumRegsLeft); 8016 } 8017 8018 return ArgInfo; 8019 } 8020 8021 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo { 8022 public: 8023 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT) 8024 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {} 8025 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8026 CodeGen::CodeGenModule &M) const override; 8027 unsigned getOpenCLKernelCallingConv() const override; 8028 8029 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM, 8030 llvm::PointerType *T, QualType QT) const override; 8031 8032 LangAS getASTAllocaAddressSpace() const override { 8033 return getLangASFromTargetAS( 8034 getABIInfo().getDataLayout().getAllocaAddrSpace()); 8035 } 8036 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, 8037 const VarDecl *D) const override; 8038 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts, 8039 SyncScope Scope, 8040 llvm::AtomicOrdering Ordering, 8041 llvm::LLVMContext &Ctx) const override; 8042 llvm::Function * 8043 createEnqueuedBlockKernel(CodeGenFunction &CGF, 8044 llvm::Function *BlockInvokeFunc, 8045 llvm::Value *BlockLiteral) const override; 8046 bool shouldEmitStaticExternCAliases() const override; 8047 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override; 8048 }; 8049 } 8050 8051 static bool requiresAMDGPUProtectedVisibility(const Decl *D, 8052 llvm::GlobalValue *GV) { 8053 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility) 8054 return false; 8055 8056 return D->hasAttr<OpenCLKernelAttr>() || 8057 (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) || 8058 (isa<VarDecl>(D) && 8059 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 8060 D->hasAttr<HIPPinnedShadowAttr>())); 8061 } 8062 8063 static bool requiresAMDGPUDefaultVisibility(const Decl *D, 8064 llvm::GlobalValue *GV) { 8065 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility) 8066 return false; 8067 8068 return isa<VarDecl>(D) && D->hasAttr<HIPPinnedShadowAttr>(); 8069 } 8070 8071 void AMDGPUTargetCodeGenInfo::setTargetAttributes( 8072 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8073 if (requiresAMDGPUDefaultVisibility(D, GV)) { 8074 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 8075 GV->setDSOLocal(false); 8076 } else if (requiresAMDGPUProtectedVisibility(D, GV)) { 8077 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 8078 GV->setDSOLocal(true); 8079 } 8080 8081 if (GV->isDeclaration()) 8082 return; 8083 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8084 if (!FD) 8085 return; 8086 8087 llvm::Function *F = cast<llvm::Function>(GV); 8088 8089 const auto *ReqdWGS = M.getLangOpts().OpenCL ? 8090 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr; 8091 8092 8093 const bool IsOpenCLKernel = M.getLangOpts().OpenCL && 8094 FD->hasAttr<OpenCLKernelAttr>(); 8095 const bool IsHIPKernel = M.getLangOpts().HIP && 8096 FD->hasAttr<CUDAGlobalAttr>(); 8097 if ((IsOpenCLKernel || IsHIPKernel) && 8098 (M.getTriple().getOS() == llvm::Triple::AMDHSA)) 8099 F->addFnAttr("amdgpu-implicitarg-num-bytes", "56"); 8100 8101 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>(); 8102 if (ReqdWGS || FlatWGS) { 8103 unsigned Min = 0; 8104 unsigned Max = 0; 8105 if (FlatWGS) { 8106 Min = FlatWGS->getMin() 8107 ->EvaluateKnownConstInt(M.getContext()) 8108 .getExtValue(); 8109 Max = FlatWGS->getMax() 8110 ->EvaluateKnownConstInt(M.getContext()) 8111 .getExtValue(); 8112 } 8113 if (ReqdWGS && Min == 0 && Max == 0) 8114 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim(); 8115 8116 if (Min != 0) { 8117 assert(Min <= Max && "Min must be less than or equal Max"); 8118 8119 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max); 8120 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 8121 } else 8122 assert(Max == 0 && "Max must be zero"); 8123 } else if (IsOpenCLKernel || IsHIPKernel) { 8124 // By default, restrict the maximum size to a value specified by 8125 // --gpu-max-threads-per-block=n or its default value. 8126 std::string AttrVal = 8127 std::string("1,") + llvm::utostr(M.getLangOpts().GPUMaxThreadsPerBlock); 8128 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 8129 } 8130 8131 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) { 8132 unsigned Min = 8133 Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue(); 8134 unsigned Max = Attr->getMax() ? Attr->getMax() 8135 ->EvaluateKnownConstInt(M.getContext()) 8136 .getExtValue() 8137 : 0; 8138 8139 if (Min != 0) { 8140 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max"); 8141 8142 std::string AttrVal = llvm::utostr(Min); 8143 if (Max != 0) 8144 AttrVal = AttrVal + "," + llvm::utostr(Max); 8145 F->addFnAttr("amdgpu-waves-per-eu", AttrVal); 8146 } else 8147 assert(Max == 0 && "Max must be zero"); 8148 } 8149 8150 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) { 8151 unsigned NumSGPR = Attr->getNumSGPR(); 8152 8153 if (NumSGPR != 0) 8154 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR)); 8155 } 8156 8157 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) { 8158 uint32_t NumVGPR = Attr->getNumVGPR(); 8159 8160 if (NumVGPR != 0) 8161 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR)); 8162 } 8163 } 8164 8165 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 8166 return llvm::CallingConv::AMDGPU_KERNEL; 8167 } 8168 8169 // Currently LLVM assumes null pointers always have value 0, 8170 // which results in incorrectly transformed IR. Therefore, instead of 8171 // emitting null pointers in private and local address spaces, a null 8172 // pointer in generic address space is emitted which is casted to a 8173 // pointer in local or private address space. 8174 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer( 8175 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT, 8176 QualType QT) const { 8177 if (CGM.getContext().getTargetNullPointerValue(QT) == 0) 8178 return llvm::ConstantPointerNull::get(PT); 8179 8180 auto &Ctx = CGM.getContext(); 8181 auto NPT = llvm::PointerType::get(PT->getElementType(), 8182 Ctx.getTargetAddressSpace(LangAS::opencl_generic)); 8183 return llvm::ConstantExpr::getAddrSpaceCast( 8184 llvm::ConstantPointerNull::get(NPT), PT); 8185 } 8186 8187 LangAS 8188 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 8189 const VarDecl *D) const { 8190 assert(!CGM.getLangOpts().OpenCL && 8191 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 8192 "Address space agnostic languages only"); 8193 LangAS DefaultGlobalAS = getLangASFromTargetAS( 8194 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global)); 8195 if (!D) 8196 return DefaultGlobalAS; 8197 8198 LangAS AddrSpace = D->getType().getAddressSpace(); 8199 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace)); 8200 if (AddrSpace != LangAS::Default) 8201 return AddrSpace; 8202 8203 if (CGM.isTypeConstant(D->getType(), false)) { 8204 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace()) 8205 return ConstAS.getValue(); 8206 } 8207 return DefaultGlobalAS; 8208 } 8209 8210 llvm::SyncScope::ID 8211 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 8212 SyncScope Scope, 8213 llvm::AtomicOrdering Ordering, 8214 llvm::LLVMContext &Ctx) const { 8215 std::string Name; 8216 switch (Scope) { 8217 case SyncScope::OpenCLWorkGroup: 8218 Name = "workgroup"; 8219 break; 8220 case SyncScope::OpenCLDevice: 8221 Name = "agent"; 8222 break; 8223 case SyncScope::OpenCLAllSVMDevices: 8224 Name = ""; 8225 break; 8226 case SyncScope::OpenCLSubGroup: 8227 Name = "wavefront"; 8228 } 8229 8230 if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) { 8231 if (!Name.empty()) 8232 Name = Twine(Twine(Name) + Twine("-")).str(); 8233 8234 Name = Twine(Twine(Name) + Twine("one-as")).str(); 8235 } 8236 8237 return Ctx.getOrInsertSyncScopeID(Name); 8238 } 8239 8240 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 8241 return false; 8242 } 8243 8244 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention( 8245 const FunctionType *&FT) const { 8246 FT = getABIInfo().getContext().adjustFunctionType( 8247 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel)); 8248 } 8249 8250 //===----------------------------------------------------------------------===// 8251 // SPARC v8 ABI Implementation. 8252 // Based on the SPARC Compliance Definition version 2.4.1. 8253 // 8254 // Ensures that complex values are passed in registers. 8255 // 8256 namespace { 8257 class SparcV8ABIInfo : public DefaultABIInfo { 8258 public: 8259 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8260 8261 private: 8262 ABIArgInfo classifyReturnType(QualType RetTy) const; 8263 void computeInfo(CGFunctionInfo &FI) const override; 8264 }; 8265 } // end anonymous namespace 8266 8267 8268 ABIArgInfo 8269 SparcV8ABIInfo::classifyReturnType(QualType Ty) const { 8270 if (Ty->isAnyComplexType()) { 8271 return ABIArgInfo::getDirect(); 8272 } 8273 else { 8274 return DefaultABIInfo::classifyReturnType(Ty); 8275 } 8276 } 8277 8278 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const { 8279 8280 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8281 for (auto &Arg : FI.arguments()) 8282 Arg.info = classifyArgumentType(Arg.type); 8283 } 8284 8285 namespace { 8286 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo { 8287 public: 8288 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT) 8289 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {} 8290 }; 8291 } // end anonymous namespace 8292 8293 //===----------------------------------------------------------------------===// 8294 // SPARC v9 ABI Implementation. 8295 // Based on the SPARC Compliance Definition version 2.4.1. 8296 // 8297 // Function arguments a mapped to a nominal "parameter array" and promoted to 8298 // registers depending on their type. Each argument occupies 8 or 16 bytes in 8299 // the array, structs larger than 16 bytes are passed indirectly. 8300 // 8301 // One case requires special care: 8302 // 8303 // struct mixed { 8304 // int i; 8305 // float f; 8306 // }; 8307 // 8308 // When a struct mixed is passed by value, it only occupies 8 bytes in the 8309 // parameter array, but the int is passed in an integer register, and the float 8310 // is passed in a floating point register. This is represented as two arguments 8311 // with the LLVM IR inreg attribute: 8312 // 8313 // declare void f(i32 inreg %i, float inreg %f) 8314 // 8315 // The code generator will only allocate 4 bytes from the parameter array for 8316 // the inreg arguments. All other arguments are allocated a multiple of 8 8317 // bytes. 8318 // 8319 namespace { 8320 class SparcV9ABIInfo : public ABIInfo { 8321 public: 8322 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 8323 8324 private: 8325 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const; 8326 void computeInfo(CGFunctionInfo &FI) const override; 8327 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8328 QualType Ty) const override; 8329 8330 // Coercion type builder for structs passed in registers. The coercion type 8331 // serves two purposes: 8332 // 8333 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned' 8334 // in registers. 8335 // 2. Expose aligned floating point elements as first-level elements, so the 8336 // code generator knows to pass them in floating point registers. 8337 // 8338 // We also compute the InReg flag which indicates that the struct contains 8339 // aligned 32-bit floats. 8340 // 8341 struct CoerceBuilder { 8342 llvm::LLVMContext &Context; 8343 const llvm::DataLayout &DL; 8344 SmallVector<llvm::Type*, 8> Elems; 8345 uint64_t Size; 8346 bool InReg; 8347 8348 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl) 8349 : Context(c), DL(dl), Size(0), InReg(false) {} 8350 8351 // Pad Elems with integers until Size is ToSize. 8352 void pad(uint64_t ToSize) { 8353 assert(ToSize >= Size && "Cannot remove elements"); 8354 if (ToSize == Size) 8355 return; 8356 8357 // Finish the current 64-bit word. 8358 uint64_t Aligned = llvm::alignTo(Size, 64); 8359 if (Aligned > Size && Aligned <= ToSize) { 8360 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size)); 8361 Size = Aligned; 8362 } 8363 8364 // Add whole 64-bit words. 8365 while (Size + 64 <= ToSize) { 8366 Elems.push_back(llvm::Type::getInt64Ty(Context)); 8367 Size += 64; 8368 } 8369 8370 // Final in-word padding. 8371 if (Size < ToSize) { 8372 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size)); 8373 Size = ToSize; 8374 } 8375 } 8376 8377 // Add a floating point element at Offset. 8378 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) { 8379 // Unaligned floats are treated as integers. 8380 if (Offset % Bits) 8381 return; 8382 // The InReg flag is only required if there are any floats < 64 bits. 8383 if (Bits < 64) 8384 InReg = true; 8385 pad(Offset); 8386 Elems.push_back(Ty); 8387 Size = Offset + Bits; 8388 } 8389 8390 // Add a struct type to the coercion type, starting at Offset (in bits). 8391 void addStruct(uint64_t Offset, llvm::StructType *StrTy) { 8392 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy); 8393 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) { 8394 llvm::Type *ElemTy = StrTy->getElementType(i); 8395 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i); 8396 switch (ElemTy->getTypeID()) { 8397 case llvm::Type::StructTyID: 8398 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy)); 8399 break; 8400 case llvm::Type::FloatTyID: 8401 addFloat(ElemOffset, ElemTy, 32); 8402 break; 8403 case llvm::Type::DoubleTyID: 8404 addFloat(ElemOffset, ElemTy, 64); 8405 break; 8406 case llvm::Type::FP128TyID: 8407 addFloat(ElemOffset, ElemTy, 128); 8408 break; 8409 case llvm::Type::PointerTyID: 8410 if (ElemOffset % 64 == 0) { 8411 pad(ElemOffset); 8412 Elems.push_back(ElemTy); 8413 Size += 64; 8414 } 8415 break; 8416 default: 8417 break; 8418 } 8419 } 8420 } 8421 8422 // Check if Ty is a usable substitute for the coercion type. 8423 bool isUsableType(llvm::StructType *Ty) const { 8424 return llvm::makeArrayRef(Elems) == Ty->elements(); 8425 } 8426 8427 // Get the coercion type as a literal struct type. 8428 llvm::Type *getType() const { 8429 if (Elems.size() == 1) 8430 return Elems.front(); 8431 else 8432 return llvm::StructType::get(Context, Elems); 8433 } 8434 }; 8435 }; 8436 } // end anonymous namespace 8437 8438 ABIArgInfo 8439 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const { 8440 if (Ty->isVoidType()) 8441 return ABIArgInfo::getIgnore(); 8442 8443 uint64_t Size = getContext().getTypeSize(Ty); 8444 8445 // Anything too big to fit in registers is passed with an explicit indirect 8446 // pointer / sret pointer. 8447 if (Size > SizeLimit) 8448 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 8449 8450 // Treat an enum type as its underlying type. 8451 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 8452 Ty = EnumTy->getDecl()->getIntegerType(); 8453 8454 // Integer types smaller than a register are extended. 8455 if (Size < 64 && Ty->isIntegerType()) 8456 return ABIArgInfo::getExtend(Ty); 8457 8458 // Other non-aggregates go in registers. 8459 if (!isAggregateTypeForABI(Ty)) 8460 return ABIArgInfo::getDirect(); 8461 8462 // If a C++ object has either a non-trivial copy constructor or a non-trivial 8463 // destructor, it is passed with an explicit indirect pointer / sret pointer. 8464 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 8465 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8466 8467 // This is a small aggregate type that should be passed in registers. 8468 // Build a coercion type from the LLVM struct type. 8469 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty)); 8470 if (!StrTy) 8471 return ABIArgInfo::getDirect(); 8472 8473 CoerceBuilder CB(getVMContext(), getDataLayout()); 8474 CB.addStruct(0, StrTy); 8475 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64)); 8476 8477 // Try to use the original type for coercion. 8478 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType(); 8479 8480 if (CB.InReg) 8481 return ABIArgInfo::getDirectInReg(CoerceTy); 8482 else 8483 return ABIArgInfo::getDirect(CoerceTy); 8484 } 8485 8486 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8487 QualType Ty) const { 8488 ABIArgInfo AI = classifyType(Ty, 16 * 8); 8489 llvm::Type *ArgTy = CGT.ConvertType(Ty); 8490 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 8491 AI.setCoerceToType(ArgTy); 8492 8493 CharUnits SlotSize = CharUnits::fromQuantity(8); 8494 8495 CGBuilderTy &Builder = CGF.Builder; 8496 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 8497 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 8498 8499 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 8500 8501 Address ArgAddr = Address::invalid(); 8502 CharUnits Stride; 8503 switch (AI.getKind()) { 8504 case ABIArgInfo::Expand: 8505 case ABIArgInfo::CoerceAndExpand: 8506 case ABIArgInfo::InAlloca: 8507 llvm_unreachable("Unsupported ABI kind for va_arg"); 8508 8509 case ABIArgInfo::Extend: { 8510 Stride = SlotSize; 8511 CharUnits Offset = SlotSize - TypeInfo.first; 8512 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend"); 8513 break; 8514 } 8515 8516 case ABIArgInfo::Direct: { 8517 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 8518 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize); 8519 ArgAddr = Addr; 8520 break; 8521 } 8522 8523 case ABIArgInfo::Indirect: 8524 Stride = SlotSize; 8525 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect"); 8526 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"), 8527 TypeInfo.second); 8528 break; 8529 8530 case ABIArgInfo::Ignore: 8531 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second); 8532 } 8533 8534 // Update VAList. 8535 Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next"); 8536 Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 8537 8538 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr"); 8539 } 8540 8541 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const { 8542 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8); 8543 for (auto &I : FI.arguments()) 8544 I.info = classifyType(I.type, 16 * 8); 8545 } 8546 8547 namespace { 8548 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo { 8549 public: 8550 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT) 8551 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {} 8552 8553 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 8554 return 14; 8555 } 8556 8557 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 8558 llvm::Value *Address) const override; 8559 }; 8560 } // end anonymous namespace 8561 8562 bool 8563 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 8564 llvm::Value *Address) const { 8565 // This is calculated from the LLVM and GCC tables and verified 8566 // against gcc output. AFAIK all ABIs use the same encoding. 8567 8568 CodeGen::CGBuilderTy &Builder = CGF.Builder; 8569 8570 llvm::IntegerType *i8 = CGF.Int8Ty; 8571 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 8572 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 8573 8574 // 0-31: the 8-byte general-purpose registers 8575 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 8576 8577 // 32-63: f0-31, the 4-byte floating-point registers 8578 AssignToArrayRange(Builder, Address, Four8, 32, 63); 8579 8580 // Y = 64 8581 // PSR = 65 8582 // WIM = 66 8583 // TBR = 67 8584 // PC = 68 8585 // NPC = 69 8586 // FSR = 70 8587 // CSR = 71 8588 AssignToArrayRange(Builder, Address, Eight8, 64, 71); 8589 8590 // 72-87: d0-15, the 8-byte floating-point registers 8591 AssignToArrayRange(Builder, Address, Eight8, 72, 87); 8592 8593 return false; 8594 } 8595 8596 // ARC ABI implementation. 8597 namespace { 8598 8599 class ARCABIInfo : public DefaultABIInfo { 8600 public: 8601 using DefaultABIInfo::DefaultABIInfo; 8602 8603 private: 8604 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8605 QualType Ty) const override; 8606 8607 void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const { 8608 if (!State.FreeRegs) 8609 return; 8610 if (Info.isIndirect() && Info.getInReg()) 8611 State.FreeRegs--; 8612 else if (Info.isDirect() && Info.getInReg()) { 8613 unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32; 8614 if (sz < State.FreeRegs) 8615 State.FreeRegs -= sz; 8616 else 8617 State.FreeRegs = 0; 8618 } 8619 } 8620 8621 void computeInfo(CGFunctionInfo &FI) const override { 8622 CCState State(FI); 8623 // ARC uses 8 registers to pass arguments. 8624 State.FreeRegs = 8; 8625 8626 if (!getCXXABI().classifyReturnType(FI)) 8627 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8628 updateState(FI.getReturnInfo(), FI.getReturnType(), State); 8629 for (auto &I : FI.arguments()) { 8630 I.info = classifyArgumentType(I.type, State.FreeRegs); 8631 updateState(I.info, I.type, State); 8632 } 8633 } 8634 8635 ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const; 8636 ABIArgInfo getIndirectByValue(QualType Ty) const; 8637 ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const; 8638 ABIArgInfo classifyReturnType(QualType RetTy) const; 8639 }; 8640 8641 class ARCTargetCodeGenInfo : public TargetCodeGenInfo { 8642 public: 8643 ARCTargetCodeGenInfo(CodeGenTypes &CGT) 8644 : TargetCodeGenInfo(new ARCABIInfo(CGT)) {} 8645 }; 8646 8647 8648 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const { 8649 return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) : 8650 getNaturalAlignIndirect(Ty, false); 8651 } 8652 8653 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const { 8654 // Compute the byval alignment. 8655 const unsigned MinABIStackAlignInBytes = 4; 8656 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 8657 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 8658 TypeAlign > MinABIStackAlignInBytes); 8659 } 8660 8661 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8662 QualType Ty) const { 8663 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 8664 getContext().getTypeInfoInChars(Ty), 8665 CharUnits::fromQuantity(4), true); 8666 } 8667 8668 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty, 8669 uint8_t FreeRegs) const { 8670 // Handle the generic C++ ABI. 8671 const RecordType *RT = Ty->getAs<RecordType>(); 8672 if (RT) { 8673 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 8674 if (RAA == CGCXXABI::RAA_Indirect) 8675 return getIndirectByRef(Ty, FreeRegs > 0); 8676 8677 if (RAA == CGCXXABI::RAA_DirectInMemory) 8678 return getIndirectByValue(Ty); 8679 } 8680 8681 // Treat an enum type as its underlying type. 8682 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 8683 Ty = EnumTy->getDecl()->getIntegerType(); 8684 8685 auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32; 8686 8687 if (isAggregateTypeForABI(Ty)) { 8688 // Structures with flexible arrays are always indirect. 8689 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 8690 return getIndirectByValue(Ty); 8691 8692 // Ignore empty structs/unions. 8693 if (isEmptyRecord(getContext(), Ty, true)) 8694 return ABIArgInfo::getIgnore(); 8695 8696 llvm::LLVMContext &LLVMContext = getVMContext(); 8697 8698 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 8699 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 8700 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 8701 8702 return FreeRegs >= SizeInRegs ? 8703 ABIArgInfo::getDirectInReg(Result) : 8704 ABIArgInfo::getDirect(Result, 0, nullptr, false); 8705 } 8706 8707 return Ty->isPromotableIntegerType() ? 8708 (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) : 8709 ABIArgInfo::getExtend(Ty)) : 8710 (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() : 8711 ABIArgInfo::getDirect()); 8712 } 8713 8714 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const { 8715 if (RetTy->isAnyComplexType()) 8716 return ABIArgInfo::getDirectInReg(); 8717 8718 // Arguments of size > 4 registers are indirect. 8719 auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32; 8720 if (RetSize > 4) 8721 return getIndirectByRef(RetTy, /*HasFreeRegs*/ true); 8722 8723 return DefaultABIInfo::classifyReturnType(RetTy); 8724 } 8725 8726 } // End anonymous namespace. 8727 8728 //===----------------------------------------------------------------------===// 8729 // XCore ABI Implementation 8730 //===----------------------------------------------------------------------===// 8731 8732 namespace { 8733 8734 /// A SmallStringEnc instance is used to build up the TypeString by passing 8735 /// it by reference between functions that append to it. 8736 typedef llvm::SmallString<128> SmallStringEnc; 8737 8738 /// TypeStringCache caches the meta encodings of Types. 8739 /// 8740 /// The reason for caching TypeStrings is two fold: 8741 /// 1. To cache a type's encoding for later uses; 8742 /// 2. As a means to break recursive member type inclusion. 8743 /// 8744 /// A cache Entry can have a Status of: 8745 /// NonRecursive: The type encoding is not recursive; 8746 /// Recursive: The type encoding is recursive; 8747 /// Incomplete: An incomplete TypeString; 8748 /// IncompleteUsed: An incomplete TypeString that has been used in a 8749 /// Recursive type encoding. 8750 /// 8751 /// A NonRecursive entry will have all of its sub-members expanded as fully 8752 /// as possible. Whilst it may contain types which are recursive, the type 8753 /// itself is not recursive and thus its encoding may be safely used whenever 8754 /// the type is encountered. 8755 /// 8756 /// A Recursive entry will have all of its sub-members expanded as fully as 8757 /// possible. The type itself is recursive and it may contain other types which 8758 /// are recursive. The Recursive encoding must not be used during the expansion 8759 /// of a recursive type's recursive branch. For simplicity the code uses 8760 /// IncompleteCount to reject all usage of Recursive encodings for member types. 8761 /// 8762 /// An Incomplete entry is always a RecordType and only encodes its 8763 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and 8764 /// are placed into the cache during type expansion as a means to identify and 8765 /// handle recursive inclusion of types as sub-members. If there is recursion 8766 /// the entry becomes IncompleteUsed. 8767 /// 8768 /// During the expansion of a RecordType's members: 8769 /// 8770 /// If the cache contains a NonRecursive encoding for the member type, the 8771 /// cached encoding is used; 8772 /// 8773 /// If the cache contains a Recursive encoding for the member type, the 8774 /// cached encoding is 'Swapped' out, as it may be incorrect, and... 8775 /// 8776 /// If the member is a RecordType, an Incomplete encoding is placed into the 8777 /// cache to break potential recursive inclusion of itself as a sub-member; 8778 /// 8779 /// Once a member RecordType has been expanded, its temporary incomplete 8780 /// entry is removed from the cache. If a Recursive encoding was swapped out 8781 /// it is swapped back in; 8782 /// 8783 /// If an incomplete entry is used to expand a sub-member, the incomplete 8784 /// entry is marked as IncompleteUsed. The cache keeps count of how many 8785 /// IncompleteUsed entries it currently contains in IncompleteUsedCount; 8786 /// 8787 /// If a member's encoding is found to be a NonRecursive or Recursive viz: 8788 /// IncompleteUsedCount==0, the member's encoding is added to the cache. 8789 /// Else the member is part of a recursive type and thus the recursion has 8790 /// been exited too soon for the encoding to be correct for the member. 8791 /// 8792 class TypeStringCache { 8793 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed}; 8794 struct Entry { 8795 std::string Str; // The encoded TypeString for the type. 8796 enum Status State; // Information about the encoding in 'Str'. 8797 std::string Swapped; // A temporary place holder for a Recursive encoding 8798 // during the expansion of RecordType's members. 8799 }; 8800 std::map<const IdentifierInfo *, struct Entry> Map; 8801 unsigned IncompleteCount; // Number of Incomplete entries in the Map. 8802 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map. 8803 public: 8804 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {} 8805 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc); 8806 bool removeIncomplete(const IdentifierInfo *ID); 8807 void addIfComplete(const IdentifierInfo *ID, StringRef Str, 8808 bool IsRecursive); 8809 StringRef lookupStr(const IdentifierInfo *ID); 8810 }; 8811 8812 /// TypeString encodings for enum & union fields must be order. 8813 /// FieldEncoding is a helper for this ordering process. 8814 class FieldEncoding { 8815 bool HasName; 8816 std::string Enc; 8817 public: 8818 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {} 8819 StringRef str() { return Enc; } 8820 bool operator<(const FieldEncoding &rhs) const { 8821 if (HasName != rhs.HasName) return HasName; 8822 return Enc < rhs.Enc; 8823 } 8824 }; 8825 8826 class XCoreABIInfo : public DefaultABIInfo { 8827 public: 8828 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8829 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8830 QualType Ty) const override; 8831 }; 8832 8833 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo { 8834 mutable TypeStringCache TSC; 8835 public: 8836 XCoreTargetCodeGenInfo(CodeGenTypes &CGT) 8837 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {} 8838 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV, 8839 CodeGen::CodeGenModule &M) const override; 8840 }; 8841 8842 } // End anonymous namespace. 8843 8844 // TODO: this implementation is likely now redundant with the default 8845 // EmitVAArg. 8846 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8847 QualType Ty) const { 8848 CGBuilderTy &Builder = CGF.Builder; 8849 8850 // Get the VAList. 8851 CharUnits SlotSize = CharUnits::fromQuantity(4); 8852 Address AP(Builder.CreateLoad(VAListAddr), SlotSize); 8853 8854 // Handle the argument. 8855 ABIArgInfo AI = classifyArgumentType(Ty); 8856 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty); 8857 llvm::Type *ArgTy = CGT.ConvertType(Ty); 8858 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 8859 AI.setCoerceToType(ArgTy); 8860 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 8861 8862 Address Val = Address::invalid(); 8863 CharUnits ArgSize = CharUnits::Zero(); 8864 switch (AI.getKind()) { 8865 case ABIArgInfo::Expand: 8866 case ABIArgInfo::CoerceAndExpand: 8867 case ABIArgInfo::InAlloca: 8868 llvm_unreachable("Unsupported ABI kind for va_arg"); 8869 case ABIArgInfo::Ignore: 8870 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign); 8871 ArgSize = CharUnits::Zero(); 8872 break; 8873 case ABIArgInfo::Extend: 8874 case ABIArgInfo::Direct: 8875 Val = Builder.CreateBitCast(AP, ArgPtrTy); 8876 ArgSize = CharUnits::fromQuantity( 8877 getDataLayout().getTypeAllocSize(AI.getCoerceToType())); 8878 ArgSize = ArgSize.alignTo(SlotSize); 8879 break; 8880 case ABIArgInfo::Indirect: 8881 Val = Builder.CreateElementBitCast(AP, ArgPtrTy); 8882 Val = Address(Builder.CreateLoad(Val), TypeAlign); 8883 ArgSize = SlotSize; 8884 break; 8885 } 8886 8887 // Increment the VAList. 8888 if (!ArgSize.isZero()) { 8889 Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize); 8890 Builder.CreateStore(APN.getPointer(), VAListAddr); 8891 } 8892 8893 return Val; 8894 } 8895 8896 /// During the expansion of a RecordType, an incomplete TypeString is placed 8897 /// into the cache as a means to identify and break recursion. 8898 /// If there is a Recursive encoding in the cache, it is swapped out and will 8899 /// be reinserted by removeIncomplete(). 8900 /// All other types of encoding should have been used rather than arriving here. 8901 void TypeStringCache::addIncomplete(const IdentifierInfo *ID, 8902 std::string StubEnc) { 8903 if (!ID) 8904 return; 8905 Entry &E = Map[ID]; 8906 assert( (E.Str.empty() || E.State == Recursive) && 8907 "Incorrectly use of addIncomplete"); 8908 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()"); 8909 E.Swapped.swap(E.Str); // swap out the Recursive 8910 E.Str.swap(StubEnc); 8911 E.State = Incomplete; 8912 ++IncompleteCount; 8913 } 8914 8915 /// Once the RecordType has been expanded, the temporary incomplete TypeString 8916 /// must be removed from the cache. 8917 /// If a Recursive was swapped out by addIncomplete(), it will be replaced. 8918 /// Returns true if the RecordType was defined recursively. 8919 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) { 8920 if (!ID) 8921 return false; 8922 auto I = Map.find(ID); 8923 assert(I != Map.end() && "Entry not present"); 8924 Entry &E = I->second; 8925 assert( (E.State == Incomplete || 8926 E.State == IncompleteUsed) && 8927 "Entry must be an incomplete type"); 8928 bool IsRecursive = false; 8929 if (E.State == IncompleteUsed) { 8930 // We made use of our Incomplete encoding, thus we are recursive. 8931 IsRecursive = true; 8932 --IncompleteUsedCount; 8933 } 8934 if (E.Swapped.empty()) 8935 Map.erase(I); 8936 else { 8937 // Swap the Recursive back. 8938 E.Swapped.swap(E.Str); 8939 E.Swapped.clear(); 8940 E.State = Recursive; 8941 } 8942 --IncompleteCount; 8943 return IsRecursive; 8944 } 8945 8946 /// Add the encoded TypeString to the cache only if it is NonRecursive or 8947 /// Recursive (viz: all sub-members were expanded as fully as possible). 8948 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str, 8949 bool IsRecursive) { 8950 if (!ID || IncompleteUsedCount) 8951 return; // No key or it is is an incomplete sub-type so don't add. 8952 Entry &E = Map[ID]; 8953 if (IsRecursive && !E.Str.empty()) { 8954 assert(E.State==Recursive && E.Str.size() == Str.size() && 8955 "This is not the same Recursive entry"); 8956 // The parent container was not recursive after all, so we could have used 8957 // this Recursive sub-member entry after all, but we assumed the worse when 8958 // we started viz: IncompleteCount!=0. 8959 return; 8960 } 8961 assert(E.Str.empty() && "Entry already present"); 8962 E.Str = Str.str(); 8963 E.State = IsRecursive? Recursive : NonRecursive; 8964 } 8965 8966 /// Return a cached TypeString encoding for the ID. If there isn't one, or we 8967 /// are recursively expanding a type (IncompleteCount != 0) and the cached 8968 /// encoding is Recursive, return an empty StringRef. 8969 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) { 8970 if (!ID) 8971 return StringRef(); // We have no key. 8972 auto I = Map.find(ID); 8973 if (I == Map.end()) 8974 return StringRef(); // We have no encoding. 8975 Entry &E = I->second; 8976 if (E.State == Recursive && IncompleteCount) 8977 return StringRef(); // We don't use Recursive encodings for member types. 8978 8979 if (E.State == Incomplete) { 8980 // The incomplete type is being used to break out of recursion. 8981 E.State = IncompleteUsed; 8982 ++IncompleteUsedCount; 8983 } 8984 return E.Str; 8985 } 8986 8987 /// The XCore ABI includes a type information section that communicates symbol 8988 /// type information to the linker. The linker uses this information to verify 8989 /// safety/correctness of things such as array bound and pointers et al. 8990 /// The ABI only requires C (and XC) language modules to emit TypeStrings. 8991 /// This type information (TypeString) is emitted into meta data for all global 8992 /// symbols: definitions, declarations, functions & variables. 8993 /// 8994 /// The TypeString carries type, qualifier, name, size & value details. 8995 /// Please see 'Tools Development Guide' section 2.16.2 for format details: 8996 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf 8997 /// The output is tested by test/CodeGen/xcore-stringtype.c. 8998 /// 8999 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 9000 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC); 9001 9002 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols. 9003 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV, 9004 CodeGen::CodeGenModule &CGM) const { 9005 SmallStringEnc Enc; 9006 if (getTypeString(Enc, D, CGM, TSC)) { 9007 llvm::LLVMContext &Ctx = CGM.getModule().getContext(); 9008 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV), 9009 llvm::MDString::get(Ctx, Enc.str())}; 9010 llvm::NamedMDNode *MD = 9011 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings"); 9012 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 9013 } 9014 } 9015 9016 //===----------------------------------------------------------------------===// 9017 // SPIR ABI Implementation 9018 //===----------------------------------------------------------------------===// 9019 9020 namespace { 9021 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo { 9022 public: 9023 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 9024 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 9025 unsigned getOpenCLKernelCallingConv() const override; 9026 }; 9027 9028 } // End anonymous namespace. 9029 9030 namespace clang { 9031 namespace CodeGen { 9032 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) { 9033 DefaultABIInfo SPIRABI(CGM.getTypes()); 9034 SPIRABI.computeInfo(FI); 9035 } 9036 } 9037 } 9038 9039 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 9040 return llvm::CallingConv::SPIR_KERNEL; 9041 } 9042 9043 static bool appendType(SmallStringEnc &Enc, QualType QType, 9044 const CodeGen::CodeGenModule &CGM, 9045 TypeStringCache &TSC); 9046 9047 /// Helper function for appendRecordType(). 9048 /// Builds a SmallVector containing the encoded field types in declaration 9049 /// order. 9050 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE, 9051 const RecordDecl *RD, 9052 const CodeGen::CodeGenModule &CGM, 9053 TypeStringCache &TSC) { 9054 for (const auto *Field : RD->fields()) { 9055 SmallStringEnc Enc; 9056 Enc += "m("; 9057 Enc += Field->getName(); 9058 Enc += "){"; 9059 if (Field->isBitField()) { 9060 Enc += "b("; 9061 llvm::raw_svector_ostream OS(Enc); 9062 OS << Field->getBitWidthValue(CGM.getContext()); 9063 Enc += ':'; 9064 } 9065 if (!appendType(Enc, Field->getType(), CGM, TSC)) 9066 return false; 9067 if (Field->isBitField()) 9068 Enc += ')'; 9069 Enc += '}'; 9070 FE.emplace_back(!Field->getName().empty(), Enc); 9071 } 9072 return true; 9073 } 9074 9075 /// Appends structure and union types to Enc and adds encoding to cache. 9076 /// Recursively calls appendType (via extractFieldType) for each field. 9077 /// Union types have their fields ordered according to the ABI. 9078 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT, 9079 const CodeGen::CodeGenModule &CGM, 9080 TypeStringCache &TSC, const IdentifierInfo *ID) { 9081 // Append the cached TypeString if we have one. 9082 StringRef TypeString = TSC.lookupStr(ID); 9083 if (!TypeString.empty()) { 9084 Enc += TypeString; 9085 return true; 9086 } 9087 9088 // Start to emit an incomplete TypeString. 9089 size_t Start = Enc.size(); 9090 Enc += (RT->isUnionType()? 'u' : 's'); 9091 Enc += '('; 9092 if (ID) 9093 Enc += ID->getName(); 9094 Enc += "){"; 9095 9096 // We collect all encoded fields and order as necessary. 9097 bool IsRecursive = false; 9098 const RecordDecl *RD = RT->getDecl()->getDefinition(); 9099 if (RD && !RD->field_empty()) { 9100 // An incomplete TypeString stub is placed in the cache for this RecordType 9101 // so that recursive calls to this RecordType will use it whilst building a 9102 // complete TypeString for this RecordType. 9103 SmallVector<FieldEncoding, 16> FE; 9104 std::string StubEnc(Enc.substr(Start).str()); 9105 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString. 9106 TSC.addIncomplete(ID, std::move(StubEnc)); 9107 if (!extractFieldType(FE, RD, CGM, TSC)) { 9108 (void) TSC.removeIncomplete(ID); 9109 return false; 9110 } 9111 IsRecursive = TSC.removeIncomplete(ID); 9112 // The ABI requires unions to be sorted but not structures. 9113 // See FieldEncoding::operator< for sort algorithm. 9114 if (RT->isUnionType()) 9115 llvm::sort(FE); 9116 // We can now complete the TypeString. 9117 unsigned E = FE.size(); 9118 for (unsigned I = 0; I != E; ++I) { 9119 if (I) 9120 Enc += ','; 9121 Enc += FE[I].str(); 9122 } 9123 } 9124 Enc += '}'; 9125 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive); 9126 return true; 9127 } 9128 9129 /// Appends enum types to Enc and adds the encoding to the cache. 9130 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET, 9131 TypeStringCache &TSC, 9132 const IdentifierInfo *ID) { 9133 // Append the cached TypeString if we have one. 9134 StringRef TypeString = TSC.lookupStr(ID); 9135 if (!TypeString.empty()) { 9136 Enc += TypeString; 9137 return true; 9138 } 9139 9140 size_t Start = Enc.size(); 9141 Enc += "e("; 9142 if (ID) 9143 Enc += ID->getName(); 9144 Enc += "){"; 9145 9146 // We collect all encoded enumerations and order them alphanumerically. 9147 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) { 9148 SmallVector<FieldEncoding, 16> FE; 9149 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E; 9150 ++I) { 9151 SmallStringEnc EnumEnc; 9152 EnumEnc += "m("; 9153 EnumEnc += I->getName(); 9154 EnumEnc += "){"; 9155 I->getInitVal().toString(EnumEnc); 9156 EnumEnc += '}'; 9157 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc)); 9158 } 9159 llvm::sort(FE); 9160 unsigned E = FE.size(); 9161 for (unsigned I = 0; I != E; ++I) { 9162 if (I) 9163 Enc += ','; 9164 Enc += FE[I].str(); 9165 } 9166 } 9167 Enc += '}'; 9168 TSC.addIfComplete(ID, Enc.substr(Start), false); 9169 return true; 9170 } 9171 9172 /// Appends type's qualifier to Enc. 9173 /// This is done prior to appending the type's encoding. 9174 static void appendQualifier(SmallStringEnc &Enc, QualType QT) { 9175 // Qualifiers are emitted in alphabetical order. 9176 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"}; 9177 int Lookup = 0; 9178 if (QT.isConstQualified()) 9179 Lookup += 1<<0; 9180 if (QT.isRestrictQualified()) 9181 Lookup += 1<<1; 9182 if (QT.isVolatileQualified()) 9183 Lookup += 1<<2; 9184 Enc += Table[Lookup]; 9185 } 9186 9187 /// Appends built-in types to Enc. 9188 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) { 9189 const char *EncType; 9190 switch (BT->getKind()) { 9191 case BuiltinType::Void: 9192 EncType = "0"; 9193 break; 9194 case BuiltinType::Bool: 9195 EncType = "b"; 9196 break; 9197 case BuiltinType::Char_U: 9198 EncType = "uc"; 9199 break; 9200 case BuiltinType::UChar: 9201 EncType = "uc"; 9202 break; 9203 case BuiltinType::SChar: 9204 EncType = "sc"; 9205 break; 9206 case BuiltinType::UShort: 9207 EncType = "us"; 9208 break; 9209 case BuiltinType::Short: 9210 EncType = "ss"; 9211 break; 9212 case BuiltinType::UInt: 9213 EncType = "ui"; 9214 break; 9215 case BuiltinType::Int: 9216 EncType = "si"; 9217 break; 9218 case BuiltinType::ULong: 9219 EncType = "ul"; 9220 break; 9221 case BuiltinType::Long: 9222 EncType = "sl"; 9223 break; 9224 case BuiltinType::ULongLong: 9225 EncType = "ull"; 9226 break; 9227 case BuiltinType::LongLong: 9228 EncType = "sll"; 9229 break; 9230 case BuiltinType::Float: 9231 EncType = "ft"; 9232 break; 9233 case BuiltinType::Double: 9234 EncType = "d"; 9235 break; 9236 case BuiltinType::LongDouble: 9237 EncType = "ld"; 9238 break; 9239 default: 9240 return false; 9241 } 9242 Enc += EncType; 9243 return true; 9244 } 9245 9246 /// Appends a pointer encoding to Enc before calling appendType for the pointee. 9247 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT, 9248 const CodeGen::CodeGenModule &CGM, 9249 TypeStringCache &TSC) { 9250 Enc += "p("; 9251 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC)) 9252 return false; 9253 Enc += ')'; 9254 return true; 9255 } 9256 9257 /// Appends array encoding to Enc before calling appendType for the element. 9258 static bool appendArrayType(SmallStringEnc &Enc, QualType QT, 9259 const ArrayType *AT, 9260 const CodeGen::CodeGenModule &CGM, 9261 TypeStringCache &TSC, StringRef NoSizeEnc) { 9262 if (AT->getSizeModifier() != ArrayType::Normal) 9263 return false; 9264 Enc += "a("; 9265 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 9266 CAT->getSize().toStringUnsigned(Enc); 9267 else 9268 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "". 9269 Enc += ':'; 9270 // The Qualifiers should be attached to the type rather than the array. 9271 appendQualifier(Enc, QT); 9272 if (!appendType(Enc, AT->getElementType(), CGM, TSC)) 9273 return false; 9274 Enc += ')'; 9275 return true; 9276 } 9277 9278 /// Appends a function encoding to Enc, calling appendType for the return type 9279 /// and the arguments. 9280 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT, 9281 const CodeGen::CodeGenModule &CGM, 9282 TypeStringCache &TSC) { 9283 Enc += "f{"; 9284 if (!appendType(Enc, FT->getReturnType(), CGM, TSC)) 9285 return false; 9286 Enc += "}("; 9287 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) { 9288 // N.B. we are only interested in the adjusted param types. 9289 auto I = FPT->param_type_begin(); 9290 auto E = FPT->param_type_end(); 9291 if (I != E) { 9292 do { 9293 if (!appendType(Enc, *I, CGM, TSC)) 9294 return false; 9295 ++I; 9296 if (I != E) 9297 Enc += ','; 9298 } while (I != E); 9299 if (FPT->isVariadic()) 9300 Enc += ",va"; 9301 } else { 9302 if (FPT->isVariadic()) 9303 Enc += "va"; 9304 else 9305 Enc += '0'; 9306 } 9307 } 9308 Enc += ')'; 9309 return true; 9310 } 9311 9312 /// Handles the type's qualifier before dispatching a call to handle specific 9313 /// type encodings. 9314 static bool appendType(SmallStringEnc &Enc, QualType QType, 9315 const CodeGen::CodeGenModule &CGM, 9316 TypeStringCache &TSC) { 9317 9318 QualType QT = QType.getCanonicalType(); 9319 9320 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) 9321 // The Qualifiers should be attached to the type rather than the array. 9322 // Thus we don't call appendQualifier() here. 9323 return appendArrayType(Enc, QT, AT, CGM, TSC, ""); 9324 9325 appendQualifier(Enc, QT); 9326 9327 if (const BuiltinType *BT = QT->getAs<BuiltinType>()) 9328 return appendBuiltinType(Enc, BT); 9329 9330 if (const PointerType *PT = QT->getAs<PointerType>()) 9331 return appendPointerType(Enc, PT, CGM, TSC); 9332 9333 if (const EnumType *ET = QT->getAs<EnumType>()) 9334 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier()); 9335 9336 if (const RecordType *RT = QT->getAsStructureType()) 9337 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 9338 9339 if (const RecordType *RT = QT->getAsUnionType()) 9340 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 9341 9342 if (const FunctionType *FT = QT->getAs<FunctionType>()) 9343 return appendFunctionType(Enc, FT, CGM, TSC); 9344 9345 return false; 9346 } 9347 9348 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 9349 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) { 9350 if (!D) 9351 return false; 9352 9353 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 9354 if (FD->getLanguageLinkage() != CLanguageLinkage) 9355 return false; 9356 return appendType(Enc, FD->getType(), CGM, TSC); 9357 } 9358 9359 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 9360 if (VD->getLanguageLinkage() != CLanguageLinkage) 9361 return false; 9362 QualType QT = VD->getType().getCanonicalType(); 9363 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) { 9364 // Global ArrayTypes are given a size of '*' if the size is unknown. 9365 // The Qualifiers should be attached to the type rather than the array. 9366 // Thus we don't call appendQualifier() here. 9367 return appendArrayType(Enc, QT, AT, CGM, TSC, "*"); 9368 } 9369 return appendType(Enc, QT, CGM, TSC); 9370 } 9371 return false; 9372 } 9373 9374 //===----------------------------------------------------------------------===// 9375 // RISCV ABI Implementation 9376 //===----------------------------------------------------------------------===// 9377 9378 namespace { 9379 class RISCVABIInfo : public DefaultABIInfo { 9380 private: 9381 // Size of the integer ('x') registers in bits. 9382 unsigned XLen; 9383 // Size of the floating point ('f') registers in bits. Note that the target 9384 // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target 9385 // with soft float ABI has FLen==0). 9386 unsigned FLen; 9387 static const int NumArgGPRs = 8; 9388 static const int NumArgFPRs = 8; 9389 bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 9390 llvm::Type *&Field1Ty, 9391 CharUnits &Field1Off, 9392 llvm::Type *&Field2Ty, 9393 CharUnits &Field2Off) const; 9394 9395 public: 9396 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen) 9397 : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {} 9398 9399 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 9400 // non-virtual, but computeInfo is virtual, so we overload it. 9401 void computeInfo(CGFunctionInfo &FI) const override; 9402 9403 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft, 9404 int &ArgFPRsLeft) const; 9405 ABIArgInfo classifyReturnType(QualType RetTy) const; 9406 9407 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9408 QualType Ty) const override; 9409 9410 ABIArgInfo extendType(QualType Ty) const; 9411 9412 bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 9413 CharUnits &Field1Off, llvm::Type *&Field2Ty, 9414 CharUnits &Field2Off, int &NeededArgGPRs, 9415 int &NeededArgFPRs) const; 9416 ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty, 9417 CharUnits Field1Off, 9418 llvm::Type *Field2Ty, 9419 CharUnits Field2Off) const; 9420 }; 9421 } // end anonymous namespace 9422 9423 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const { 9424 QualType RetTy = FI.getReturnType(); 9425 if (!getCXXABI().classifyReturnType(FI)) 9426 FI.getReturnInfo() = classifyReturnType(RetTy); 9427 9428 // IsRetIndirect is true if classifyArgumentType indicated the value should 9429 // be passed indirect, or if the type size is a scalar greater than 2*XLen 9430 // and not a complex type with elements <= FLen. e.g. fp128 is passed direct 9431 // in LLVM IR, relying on the backend lowering code to rewrite the argument 9432 // list and pass indirectly on RV32. 9433 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect; 9434 if (!IsRetIndirect && RetTy->isScalarType() && 9435 getContext().getTypeSize(RetTy) > (2 * XLen)) { 9436 if (RetTy->isComplexType() && FLen) { 9437 QualType EltTy = RetTy->getAs<ComplexType>()->getElementType(); 9438 IsRetIndirect = getContext().getTypeSize(EltTy) > FLen; 9439 } else { 9440 // This is a normal scalar > 2*XLen, such as fp128 on RV32. 9441 IsRetIndirect = true; 9442 } 9443 } 9444 9445 // We must track the number of GPRs used in order to conform to the RISC-V 9446 // ABI, as integer scalars passed in registers should have signext/zeroext 9447 // when promoted, but are anyext if passed on the stack. As GPR usage is 9448 // different for variadic arguments, we must also track whether we are 9449 // examining a vararg or not. 9450 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs; 9451 int ArgFPRsLeft = FLen ? NumArgFPRs : 0; 9452 int NumFixedArgs = FI.getNumRequiredArgs(); 9453 9454 int ArgNum = 0; 9455 for (auto &ArgInfo : FI.arguments()) { 9456 bool IsFixed = ArgNum < NumFixedArgs; 9457 ArgInfo.info = 9458 classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft); 9459 ArgNum++; 9460 } 9461 } 9462 9463 // Returns true if the struct is a potential candidate for the floating point 9464 // calling convention. If this function returns true, the caller is 9465 // responsible for checking that if there is only a single field then that 9466 // field is a float. 9467 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 9468 llvm::Type *&Field1Ty, 9469 CharUnits &Field1Off, 9470 llvm::Type *&Field2Ty, 9471 CharUnits &Field2Off) const { 9472 bool IsInt = Ty->isIntegralOrEnumerationType(); 9473 bool IsFloat = Ty->isRealFloatingType(); 9474 9475 if (IsInt || IsFloat) { 9476 uint64_t Size = getContext().getTypeSize(Ty); 9477 if (IsInt && Size > XLen) 9478 return false; 9479 // Can't be eligible if larger than the FP registers. Half precision isn't 9480 // currently supported on RISC-V and the ABI hasn't been confirmed, so 9481 // default to the integer ABI in that case. 9482 if (IsFloat && (Size > FLen || Size < 32)) 9483 return false; 9484 // Can't be eligible if an integer type was already found (int+int pairs 9485 // are not eligible). 9486 if (IsInt && Field1Ty && Field1Ty->isIntegerTy()) 9487 return false; 9488 if (!Field1Ty) { 9489 Field1Ty = CGT.ConvertType(Ty); 9490 Field1Off = CurOff; 9491 return true; 9492 } 9493 if (!Field2Ty) { 9494 Field2Ty = CGT.ConvertType(Ty); 9495 Field2Off = CurOff; 9496 return true; 9497 } 9498 return false; 9499 } 9500 9501 if (auto CTy = Ty->getAs<ComplexType>()) { 9502 if (Field1Ty) 9503 return false; 9504 QualType EltTy = CTy->getElementType(); 9505 if (getContext().getTypeSize(EltTy) > FLen) 9506 return false; 9507 Field1Ty = CGT.ConvertType(EltTy); 9508 Field1Off = CurOff; 9509 assert(CurOff.isZero() && "Unexpected offset for first field"); 9510 Field2Ty = Field1Ty; 9511 Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy); 9512 return true; 9513 } 9514 9515 if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) { 9516 uint64_t ArraySize = ATy->getSize().getZExtValue(); 9517 QualType EltTy = ATy->getElementType(); 9518 CharUnits EltSize = getContext().getTypeSizeInChars(EltTy); 9519 for (uint64_t i = 0; i < ArraySize; ++i) { 9520 bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty, 9521 Field1Off, Field2Ty, Field2Off); 9522 if (!Ret) 9523 return false; 9524 CurOff += EltSize; 9525 } 9526 return true; 9527 } 9528 9529 if (const auto *RTy = Ty->getAs<RecordType>()) { 9530 // Structures with either a non-trivial destructor or a non-trivial 9531 // copy constructor are not eligible for the FP calling convention. 9532 if (getRecordArgABI(Ty, CGT.getCXXABI())) 9533 return false; 9534 if (isEmptyRecord(getContext(), Ty, true)) 9535 return true; 9536 const RecordDecl *RD = RTy->getDecl(); 9537 // Unions aren't eligible unless they're empty (which is caught above). 9538 if (RD->isUnion()) 9539 return false; 9540 int ZeroWidthBitFieldCount = 0; 9541 for (const FieldDecl *FD : RD->fields()) { 9542 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 9543 uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex()); 9544 QualType QTy = FD->getType(); 9545 if (FD->isBitField()) { 9546 unsigned BitWidth = FD->getBitWidthValue(getContext()); 9547 // Allow a bitfield with a type greater than XLen as long as the 9548 // bitwidth is XLen or less. 9549 if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen) 9550 QTy = getContext().getIntTypeForBitwidth(XLen, false); 9551 if (BitWidth == 0) { 9552 ZeroWidthBitFieldCount++; 9553 continue; 9554 } 9555 } 9556 9557 bool Ret = detectFPCCEligibleStructHelper( 9558 QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits), 9559 Field1Ty, Field1Off, Field2Ty, Field2Off); 9560 if (!Ret) 9561 return false; 9562 9563 // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp 9564 // or int+fp structs, but are ignored for a struct with an fp field and 9565 // any number of zero-width bitfields. 9566 if (Field2Ty && ZeroWidthBitFieldCount > 0) 9567 return false; 9568 } 9569 return Field1Ty != nullptr; 9570 } 9571 9572 return false; 9573 } 9574 9575 // Determine if a struct is eligible for passing according to the floating 9576 // point calling convention (i.e., when flattened it contains a single fp 9577 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and 9578 // NeededArgGPRs are incremented appropriately. 9579 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 9580 CharUnits &Field1Off, 9581 llvm::Type *&Field2Ty, 9582 CharUnits &Field2Off, 9583 int &NeededArgGPRs, 9584 int &NeededArgFPRs) const { 9585 Field1Ty = nullptr; 9586 Field2Ty = nullptr; 9587 NeededArgGPRs = 0; 9588 NeededArgFPRs = 0; 9589 bool IsCandidate = detectFPCCEligibleStructHelper( 9590 Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off); 9591 // Not really a candidate if we have a single int but no float. 9592 if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy()) 9593 return false; 9594 if (!IsCandidate) 9595 return false; 9596 if (Field1Ty && Field1Ty->isFloatingPointTy()) 9597 NeededArgFPRs++; 9598 else if (Field1Ty) 9599 NeededArgGPRs++; 9600 if (Field2Ty && Field2Ty->isFloatingPointTy()) 9601 NeededArgFPRs++; 9602 else if (Field2Ty) 9603 NeededArgGPRs++; 9604 return IsCandidate; 9605 } 9606 9607 // Call getCoerceAndExpand for the two-element flattened struct described by 9608 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an 9609 // appropriate coerceToType and unpaddedCoerceToType. 9610 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct( 9611 llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty, 9612 CharUnits Field2Off) const { 9613 SmallVector<llvm::Type *, 3> CoerceElts; 9614 SmallVector<llvm::Type *, 2> UnpaddedCoerceElts; 9615 if (!Field1Off.isZero()) 9616 CoerceElts.push_back(llvm::ArrayType::get( 9617 llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity())); 9618 9619 CoerceElts.push_back(Field1Ty); 9620 UnpaddedCoerceElts.push_back(Field1Ty); 9621 9622 if (!Field2Ty) { 9623 return ABIArgInfo::getCoerceAndExpand( 9624 llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()), 9625 UnpaddedCoerceElts[0]); 9626 } 9627 9628 CharUnits Field2Align = 9629 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty)); 9630 CharUnits Field1Size = 9631 CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty)); 9632 CharUnits Field2OffNoPadNoPack = Field1Size.alignTo(Field2Align); 9633 9634 CharUnits Padding = CharUnits::Zero(); 9635 if (Field2Off > Field2OffNoPadNoPack) 9636 Padding = Field2Off - Field2OffNoPadNoPack; 9637 else if (Field2Off != Field2Align && Field2Off > Field1Size) 9638 Padding = Field2Off - Field1Size; 9639 9640 bool IsPacked = !Field2Off.isMultipleOf(Field2Align); 9641 9642 if (!Padding.isZero()) 9643 CoerceElts.push_back(llvm::ArrayType::get( 9644 llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity())); 9645 9646 CoerceElts.push_back(Field2Ty); 9647 UnpaddedCoerceElts.push_back(Field2Ty); 9648 9649 auto CoerceToType = 9650 llvm::StructType::get(getVMContext(), CoerceElts, IsPacked); 9651 auto UnpaddedCoerceToType = 9652 llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked); 9653 9654 return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType); 9655 } 9656 9657 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed, 9658 int &ArgGPRsLeft, 9659 int &ArgFPRsLeft) const { 9660 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow"); 9661 Ty = useFirstFieldIfTransparentUnion(Ty); 9662 9663 // Structures with either a non-trivial destructor or a non-trivial 9664 // copy constructor are always passed indirectly. 9665 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 9666 if (ArgGPRsLeft) 9667 ArgGPRsLeft -= 1; 9668 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 9669 CGCXXABI::RAA_DirectInMemory); 9670 } 9671 9672 // Ignore empty structs/unions. 9673 if (isEmptyRecord(getContext(), Ty, true)) 9674 return ABIArgInfo::getIgnore(); 9675 9676 uint64_t Size = getContext().getTypeSize(Ty); 9677 9678 // Pass floating point values via FPRs if possible. 9679 if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() && 9680 FLen >= Size && ArgFPRsLeft) { 9681 ArgFPRsLeft--; 9682 return ABIArgInfo::getDirect(); 9683 } 9684 9685 // Complex types for the hard float ABI must be passed direct rather than 9686 // using CoerceAndExpand. 9687 if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) { 9688 QualType EltTy = Ty->castAs<ComplexType>()->getElementType(); 9689 if (getContext().getTypeSize(EltTy) <= FLen) { 9690 ArgFPRsLeft -= 2; 9691 return ABIArgInfo::getDirect(); 9692 } 9693 } 9694 9695 if (IsFixed && FLen && Ty->isStructureOrClassType()) { 9696 llvm::Type *Field1Ty = nullptr; 9697 llvm::Type *Field2Ty = nullptr; 9698 CharUnits Field1Off = CharUnits::Zero(); 9699 CharUnits Field2Off = CharUnits::Zero(); 9700 int NeededArgGPRs; 9701 int NeededArgFPRs; 9702 bool IsCandidate = 9703 detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off, 9704 NeededArgGPRs, NeededArgFPRs); 9705 if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft && 9706 NeededArgFPRs <= ArgFPRsLeft) { 9707 ArgGPRsLeft -= NeededArgGPRs; 9708 ArgFPRsLeft -= NeededArgFPRs; 9709 return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty, 9710 Field2Off); 9711 } 9712 } 9713 9714 uint64_t NeededAlign = getContext().getTypeAlign(Ty); 9715 bool MustUseStack = false; 9716 // Determine the number of GPRs needed to pass the current argument 9717 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned" 9718 // register pairs, so may consume 3 registers. 9719 int NeededArgGPRs = 1; 9720 if (!IsFixed && NeededAlign == 2 * XLen) 9721 NeededArgGPRs = 2 + (ArgGPRsLeft % 2); 9722 else if (Size > XLen && Size <= 2 * XLen) 9723 NeededArgGPRs = 2; 9724 9725 if (NeededArgGPRs > ArgGPRsLeft) { 9726 MustUseStack = true; 9727 NeededArgGPRs = ArgGPRsLeft; 9728 } 9729 9730 ArgGPRsLeft -= NeededArgGPRs; 9731 9732 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) { 9733 // Treat an enum type as its underlying type. 9734 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9735 Ty = EnumTy->getDecl()->getIntegerType(); 9736 9737 // All integral types are promoted to XLen width, unless passed on the 9738 // stack. 9739 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) { 9740 return extendType(Ty); 9741 } 9742 9743 return ABIArgInfo::getDirect(); 9744 } 9745 9746 // Aggregates which are <= 2*XLen will be passed in registers if possible, 9747 // so coerce to integers. 9748 if (Size <= 2 * XLen) { 9749 unsigned Alignment = getContext().getTypeAlign(Ty); 9750 9751 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is 9752 // required, and a 2-element XLen array if only XLen alignment is required. 9753 if (Size <= XLen) { 9754 return ABIArgInfo::getDirect( 9755 llvm::IntegerType::get(getVMContext(), XLen)); 9756 } else if (Alignment == 2 * XLen) { 9757 return ABIArgInfo::getDirect( 9758 llvm::IntegerType::get(getVMContext(), 2 * XLen)); 9759 } else { 9760 return ABIArgInfo::getDirect(llvm::ArrayType::get( 9761 llvm::IntegerType::get(getVMContext(), XLen), 2)); 9762 } 9763 } 9764 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 9765 } 9766 9767 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const { 9768 if (RetTy->isVoidType()) 9769 return ABIArgInfo::getIgnore(); 9770 9771 int ArgGPRsLeft = 2; 9772 int ArgFPRsLeft = FLen ? 2 : 0; 9773 9774 // The rules for return and argument types are the same, so defer to 9775 // classifyArgumentType. 9776 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft, 9777 ArgFPRsLeft); 9778 } 9779 9780 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9781 QualType Ty) const { 9782 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8); 9783 9784 // Empty records are ignored for parameter passing purposes. 9785 if (isEmptyRecord(getContext(), Ty, true)) { 9786 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 9787 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 9788 return Addr; 9789 } 9790 9791 std::pair<CharUnits, CharUnits> SizeAndAlign = 9792 getContext().getTypeInfoInChars(Ty); 9793 9794 // Arguments bigger than 2*Xlen bytes are passed indirectly. 9795 bool IsIndirect = SizeAndAlign.first > 2 * SlotSize; 9796 9797 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign, 9798 SlotSize, /*AllowHigherAlign=*/true); 9799 } 9800 9801 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const { 9802 int TySize = getContext().getTypeSize(Ty); 9803 // RV64 ABI requires unsigned 32 bit integers to be sign extended. 9804 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 9805 return ABIArgInfo::getSignExtend(Ty); 9806 return ABIArgInfo::getExtend(Ty); 9807 } 9808 9809 namespace { 9810 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo { 9811 public: 9812 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, 9813 unsigned FLen) 9814 : TargetCodeGenInfo(new RISCVABIInfo(CGT, XLen, FLen)) {} 9815 9816 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 9817 CodeGen::CodeGenModule &CGM) const override { 9818 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 9819 if (!FD) return; 9820 9821 const auto *Attr = FD->getAttr<RISCVInterruptAttr>(); 9822 if (!Attr) 9823 return; 9824 9825 const char *Kind; 9826 switch (Attr->getInterrupt()) { 9827 case RISCVInterruptAttr::user: Kind = "user"; break; 9828 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break; 9829 case RISCVInterruptAttr::machine: Kind = "machine"; break; 9830 } 9831 9832 auto *Fn = cast<llvm::Function>(GV); 9833 9834 Fn->addFnAttr("interrupt", Kind); 9835 } 9836 }; 9837 } // namespace 9838 9839 //===----------------------------------------------------------------------===// 9840 // Driver code 9841 //===----------------------------------------------------------------------===// 9842 9843 bool CodeGenModule::supportsCOMDAT() const { 9844 return getTriple().supportsCOMDAT(); 9845 } 9846 9847 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 9848 if (TheTargetCodeGenInfo) 9849 return *TheTargetCodeGenInfo; 9850 9851 // Helper to set the unique_ptr while still keeping the return value. 9852 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & { 9853 this->TheTargetCodeGenInfo.reset(P); 9854 return *P; 9855 }; 9856 9857 const llvm::Triple &Triple = getTarget().getTriple(); 9858 switch (Triple.getArch()) { 9859 default: 9860 return SetCGInfo(new DefaultTargetCodeGenInfo(Types)); 9861 9862 case llvm::Triple::le32: 9863 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 9864 case llvm::Triple::mips: 9865 case llvm::Triple::mipsel: 9866 if (Triple.getOS() == llvm::Triple::NaCl) 9867 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 9868 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true)); 9869 9870 case llvm::Triple::mips64: 9871 case llvm::Triple::mips64el: 9872 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false)); 9873 9874 case llvm::Triple::avr: 9875 return SetCGInfo(new AVRTargetCodeGenInfo(Types)); 9876 9877 case llvm::Triple::aarch64: 9878 case llvm::Triple::aarch64_32: 9879 case llvm::Triple::aarch64_be: { 9880 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS; 9881 if (getTarget().getABI() == "darwinpcs") 9882 Kind = AArch64ABIInfo::DarwinPCS; 9883 else if (Triple.isOSWindows()) 9884 return SetCGInfo( 9885 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64)); 9886 9887 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind)); 9888 } 9889 9890 case llvm::Triple::wasm32: 9891 case llvm::Triple::wasm64: 9892 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types)); 9893 9894 case llvm::Triple::arm: 9895 case llvm::Triple::armeb: 9896 case llvm::Triple::thumb: 9897 case llvm::Triple::thumbeb: { 9898 if (Triple.getOS() == llvm::Triple::Win32) { 9899 return SetCGInfo( 9900 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP)); 9901 } 9902 9903 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; 9904 StringRef ABIStr = getTarget().getABI(); 9905 if (ABIStr == "apcs-gnu") 9906 Kind = ARMABIInfo::APCS; 9907 else if (ABIStr == "aapcs16") 9908 Kind = ARMABIInfo::AAPCS16_VFP; 9909 else if (CodeGenOpts.FloatABI == "hard" || 9910 (CodeGenOpts.FloatABI != "soft" && 9911 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF || 9912 Triple.getEnvironment() == llvm::Triple::MuslEABIHF || 9913 Triple.getEnvironment() == llvm::Triple::EABIHF))) 9914 Kind = ARMABIInfo::AAPCS_VFP; 9915 9916 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind)); 9917 } 9918 9919 case llvm::Triple::ppc: { 9920 bool RetSmallStructInRegABI = 9921 PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 9922 return SetCGInfo( 9923 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft" || 9924 getTarget().hasFeature("spe"), 9925 RetSmallStructInRegABI)); 9926 } 9927 case llvm::Triple::ppc64: 9928 if (Triple.isOSBinFormatELF()) { 9929 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1; 9930 if (getTarget().getABI() == "elfv2") 9931 Kind = PPC64_SVR4_ABIInfo::ELFv2; 9932 bool HasQPX = getTarget().getABI() == "elfv1-qpx"; 9933 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 9934 9935 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX, 9936 IsSoftFloat)); 9937 } else 9938 return SetCGInfo(new PPC64TargetCodeGenInfo(Types)); 9939 case llvm::Triple::ppc64le: { 9940 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 9941 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2; 9942 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx") 9943 Kind = PPC64_SVR4_ABIInfo::ELFv1; 9944 bool HasQPX = getTarget().getABI() == "elfv1-qpx"; 9945 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 9946 9947 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX, 9948 IsSoftFloat)); 9949 } 9950 9951 case llvm::Triple::nvptx: 9952 case llvm::Triple::nvptx64: 9953 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types)); 9954 9955 case llvm::Triple::msp430: 9956 return SetCGInfo(new MSP430TargetCodeGenInfo(Types)); 9957 9958 case llvm::Triple::riscv32: 9959 case llvm::Triple::riscv64: { 9960 StringRef ABIStr = getTarget().getABI(); 9961 unsigned XLen = getTarget().getPointerWidth(0); 9962 unsigned ABIFLen = 0; 9963 if (ABIStr.endswith("f")) 9964 ABIFLen = 32; 9965 else if (ABIStr.endswith("d")) 9966 ABIFLen = 64; 9967 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen)); 9968 } 9969 9970 case llvm::Triple::systemz: { 9971 bool HasVector = getTarget().getABI() == "vector"; 9972 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector)); 9973 } 9974 9975 case llvm::Triple::tce: 9976 case llvm::Triple::tcele: 9977 return SetCGInfo(new TCETargetCodeGenInfo(Types)); 9978 9979 case llvm::Triple::x86: { 9980 bool IsDarwinVectorABI = Triple.isOSDarwin(); 9981 bool RetSmallStructInRegABI = 9982 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 9983 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); 9984 9985 if (Triple.getOS() == llvm::Triple::Win32) { 9986 return SetCGInfo(new WinX86_32TargetCodeGenInfo( 9987 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 9988 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters)); 9989 } else { 9990 return SetCGInfo(new X86_32TargetCodeGenInfo( 9991 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 9992 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters, 9993 CodeGenOpts.FloatABI == "soft")); 9994 } 9995 } 9996 9997 case llvm::Triple::x86_64: { 9998 StringRef ABI = getTarget().getABI(); 9999 X86AVXABILevel AVXLevel = 10000 (ABI == "avx512" 10001 ? X86AVXABILevel::AVX512 10002 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None); 10003 10004 switch (Triple.getOS()) { 10005 case llvm::Triple::Win32: 10006 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel)); 10007 default: 10008 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel)); 10009 } 10010 } 10011 case llvm::Triple::hexagon: 10012 return SetCGInfo(new HexagonTargetCodeGenInfo(Types)); 10013 case llvm::Triple::lanai: 10014 return SetCGInfo(new LanaiTargetCodeGenInfo(Types)); 10015 case llvm::Triple::r600: 10016 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 10017 case llvm::Triple::amdgcn: 10018 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 10019 case llvm::Triple::sparc: 10020 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types)); 10021 case llvm::Triple::sparcv9: 10022 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types)); 10023 case llvm::Triple::xcore: 10024 return SetCGInfo(new XCoreTargetCodeGenInfo(Types)); 10025 case llvm::Triple::arc: 10026 return SetCGInfo(new ARCTargetCodeGenInfo(Types)); 10027 case llvm::Triple::spir: 10028 case llvm::Triple::spir64: 10029 return SetCGInfo(new SPIRTargetCodeGenInfo(Types)); 10030 } 10031 } 10032 10033 /// Create an OpenCL kernel for an enqueued block. 10034 /// 10035 /// The kernel has the same function type as the block invoke function. Its 10036 /// name is the name of the block invoke function postfixed with "_kernel". 10037 /// It simply calls the block invoke function then returns. 10038 llvm::Function * 10039 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF, 10040 llvm::Function *Invoke, 10041 llvm::Value *BlockLiteral) const { 10042 auto *InvokeFT = Invoke->getFunctionType(); 10043 llvm::SmallVector<llvm::Type *, 2> ArgTys; 10044 for (auto &P : InvokeFT->params()) 10045 ArgTys.push_back(P); 10046 auto &C = CGF.getLLVMContext(); 10047 std::string Name = Invoke->getName().str() + "_kernel"; 10048 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 10049 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 10050 &CGF.CGM.getModule()); 10051 auto IP = CGF.Builder.saveIP(); 10052 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 10053 auto &Builder = CGF.Builder; 10054 Builder.SetInsertPoint(BB); 10055 llvm::SmallVector<llvm::Value *, 2> Args; 10056 for (auto &A : F->args()) 10057 Args.push_back(&A); 10058 Builder.CreateCall(Invoke, Args); 10059 Builder.CreateRetVoid(); 10060 Builder.restoreIP(IP); 10061 return F; 10062 } 10063 10064 /// Create an OpenCL kernel for an enqueued block. 10065 /// 10066 /// The type of the first argument (the block literal) is the struct type 10067 /// of the block literal instead of a pointer type. The first argument 10068 /// (block literal) is passed directly by value to the kernel. The kernel 10069 /// allocates the same type of struct on stack and stores the block literal 10070 /// to it and passes its pointer to the block invoke function. The kernel 10071 /// has "enqueued-block" function attribute and kernel argument metadata. 10072 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel( 10073 CodeGenFunction &CGF, llvm::Function *Invoke, 10074 llvm::Value *BlockLiteral) const { 10075 auto &Builder = CGF.Builder; 10076 auto &C = CGF.getLLVMContext(); 10077 10078 auto *BlockTy = BlockLiteral->getType()->getPointerElementType(); 10079 auto *InvokeFT = Invoke->getFunctionType(); 10080 llvm::SmallVector<llvm::Type *, 2> ArgTys; 10081 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals; 10082 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals; 10083 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames; 10084 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames; 10085 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals; 10086 llvm::SmallVector<llvm::Metadata *, 8> ArgNames; 10087 10088 ArgTys.push_back(BlockTy); 10089 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 10090 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0))); 10091 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 10092 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 10093 AccessQuals.push_back(llvm::MDString::get(C, "none")); 10094 ArgNames.push_back(llvm::MDString::get(C, "block_literal")); 10095 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) { 10096 ArgTys.push_back(InvokeFT->getParamType(I)); 10097 ArgTypeNames.push_back(llvm::MDString::get(C, "void*")); 10098 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3))); 10099 AccessQuals.push_back(llvm::MDString::get(C, "none")); 10100 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*")); 10101 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 10102 ArgNames.push_back( 10103 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str())); 10104 } 10105 std::string Name = Invoke->getName().str() + "_kernel"; 10106 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 10107 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 10108 &CGF.CGM.getModule()); 10109 F->addFnAttr("enqueued-block"); 10110 auto IP = CGF.Builder.saveIP(); 10111 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 10112 Builder.SetInsertPoint(BB); 10113 unsigned BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(BlockTy); 10114 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr); 10115 BlockPtr->setAlignment(llvm::MaybeAlign(BlockAlign)); 10116 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign); 10117 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0)); 10118 llvm::SmallVector<llvm::Value *, 2> Args; 10119 Args.push_back(Cast); 10120 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I) 10121 Args.push_back(I); 10122 Builder.CreateCall(Invoke, Args); 10123 Builder.CreateRetVoid(); 10124 Builder.restoreIP(IP); 10125 10126 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals)); 10127 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals)); 10128 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames)); 10129 F->setMetadata("kernel_arg_base_type", 10130 llvm::MDNode::get(C, ArgBaseTypeNames)); 10131 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals)); 10132 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata) 10133 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames)); 10134 10135 return F; 10136 } 10137