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