1 //===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // These classes wrap the information about a call or function 10 // definition used to handle ABI compliancy. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TargetInfo.h" 15 #include "ABIInfo.h" 16 #include "CGBlocks.h" 17 #include "CGCXXABI.h" 18 #include "CGValue.h" 19 #include "CodeGenFunction.h" 20 #include "clang/AST/Attr.h" 21 #include "clang/AST/RecordLayout.h" 22 #include "clang/Basic/CodeGenOptions.h" 23 #include "clang/Basic/DiagnosticFrontend.h" 24 #include "clang/CodeGen/CGFunctionInfo.h" 25 #include "clang/CodeGen/SwiftCallingConv.h" 26 #include "llvm/ADT/SmallBitVector.h" 27 #include "llvm/ADT/StringExtras.h" 28 #include "llvm/ADT/StringSwitch.h" 29 #include "llvm/ADT/Triple.h" 30 #include "llvm/ADT/Twine.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/IntrinsicsNVPTX.h" 33 #include "llvm/IR/Type.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include <algorithm> // std::sort 36 37 using namespace clang; 38 using namespace CodeGen; 39 40 // Helper for coercing an aggregate argument or return value into an integer 41 // array of the same size (including padding) and alignment. This alternate 42 // coercion happens only for the RenderScript ABI and can be removed after 43 // runtimes that rely on it are no longer supported. 44 // 45 // RenderScript assumes that the size of the argument / return value in the IR 46 // is the same as the size of the corresponding qualified type. This helper 47 // coerces the aggregate type into an array of the same size (including 48 // padding). This coercion is used in lieu of expansion of struct members or 49 // other canonical coercions that return a coerced-type of larger size. 50 // 51 // Ty - The argument / return value type 52 // Context - The associated ASTContext 53 // LLVMContext - The associated LLVMContext 54 static ABIArgInfo coerceToIntArray(QualType Ty, 55 ASTContext &Context, 56 llvm::LLVMContext &LLVMContext) { 57 // Alignment and Size are measured in bits. 58 const uint64_t Size = Context.getTypeSize(Ty); 59 const uint64_t Alignment = Context.getTypeAlign(Ty); 60 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment); 61 const uint64_t NumElements = (Size + Alignment - 1) / Alignment; 62 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 63 } 64 65 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder, 66 llvm::Value *Array, 67 llvm::Value *Value, 68 unsigned FirstIndex, 69 unsigned LastIndex) { 70 // Alternatively, we could emit this as a loop in the source. 71 for (unsigned I = FirstIndex; I <= LastIndex; ++I) { 72 llvm::Value *Cell = 73 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I); 74 Builder.CreateAlignedStore(Value, Cell, CharUnits::One()); 75 } 76 } 77 78 static bool isAggregateTypeForABI(QualType T) { 79 return !CodeGenFunction::hasScalarEvaluationKind(T) || 80 T->isMemberFunctionPointerType(); 81 } 82 83 ABIArgInfo ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByVal, 84 bool Realign, 85 llvm::Type *Padding) const { 86 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty), ByVal, 87 Realign, Padding); 88 } 89 90 ABIArgInfo 91 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const { 92 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty), 93 /*ByVal*/ false, Realign); 94 } 95 96 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 97 QualType Ty) const { 98 return Address::invalid(); 99 } 100 101 bool ABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const { 102 if (Ty->isPromotableIntegerType()) 103 return true; 104 105 if (const auto *EIT = Ty->getAs<ExtIntType>()) 106 if (EIT->getNumBits() < getContext().getTypeSize(getContext().IntTy)) 107 return true; 108 109 return false; 110 } 111 112 ABIInfo::~ABIInfo() {} 113 114 /// Does the given lowering require more than the given number of 115 /// registers when expanded? 116 /// 117 /// This is intended to be the basis of a reasonable basic implementation 118 /// of should{Pass,Return}IndirectlyForSwift. 119 /// 120 /// For most targets, a limit of four total registers is reasonable; this 121 /// limits the amount of code required in order to move around the value 122 /// in case it wasn't produced immediately prior to the call by the caller 123 /// (or wasn't produced in exactly the right registers) or isn't used 124 /// immediately within the callee. But some targets may need to further 125 /// limit the register count due to an inability to support that many 126 /// return registers. 127 static bool occupiesMoreThan(CodeGenTypes &cgt, 128 ArrayRef<llvm::Type*> scalarTypes, 129 unsigned maxAllRegisters) { 130 unsigned intCount = 0, fpCount = 0; 131 for (llvm::Type *type : scalarTypes) { 132 if (type->isPointerTy()) { 133 intCount++; 134 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) { 135 auto ptrWidth = cgt.getTarget().getPointerWidth(0); 136 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth; 137 } else { 138 assert(type->isVectorTy() || type->isFloatingPointTy()); 139 fpCount++; 140 } 141 } 142 143 return (intCount + fpCount > maxAllRegisters); 144 } 145 146 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 147 llvm::Type *eltTy, 148 unsigned numElts) const { 149 // The default implementation of this assumes that the target guarantees 150 // 128-bit SIMD support but nothing more. 151 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16); 152 } 153 154 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT, 155 CGCXXABI &CXXABI) { 156 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 157 if (!RD) { 158 if (!RT->getDecl()->canPassInRegisters()) 159 return CGCXXABI::RAA_Indirect; 160 return CGCXXABI::RAA_Default; 161 } 162 return CXXABI.getRecordArgABI(RD); 163 } 164 165 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T, 166 CGCXXABI &CXXABI) { 167 const RecordType *RT = T->getAs<RecordType>(); 168 if (!RT) 169 return CGCXXABI::RAA_Default; 170 return getRecordArgABI(RT, CXXABI); 171 } 172 173 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI, 174 const ABIInfo &Info) { 175 QualType Ty = FI.getReturnType(); 176 177 if (const auto *RT = Ty->getAs<RecordType>()) 178 if (!isa<CXXRecordDecl>(RT->getDecl()) && 179 !RT->getDecl()->canPassInRegisters()) { 180 FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty); 181 return true; 182 } 183 184 return CXXABI.classifyReturnType(FI); 185 } 186 187 /// Pass transparent unions as if they were the type of the first element. Sema 188 /// should ensure that all elements of the union have the same "machine type". 189 static QualType useFirstFieldIfTransparentUnion(QualType Ty) { 190 if (const RecordType *UT = Ty->getAsUnionType()) { 191 const RecordDecl *UD = UT->getDecl(); 192 if (UD->hasAttr<TransparentUnionAttr>()) { 193 assert(!UD->field_empty() && "sema created an empty transparent union"); 194 return UD->field_begin()->getType(); 195 } 196 } 197 return Ty; 198 } 199 200 CGCXXABI &ABIInfo::getCXXABI() const { 201 return CGT.getCXXABI(); 202 } 203 204 ASTContext &ABIInfo::getContext() const { 205 return CGT.getContext(); 206 } 207 208 llvm::LLVMContext &ABIInfo::getVMContext() const { 209 return CGT.getLLVMContext(); 210 } 211 212 const llvm::DataLayout &ABIInfo::getDataLayout() const { 213 return CGT.getDataLayout(); 214 } 215 216 const TargetInfo &ABIInfo::getTarget() const { 217 return CGT.getTarget(); 218 } 219 220 const CodeGenOptions &ABIInfo::getCodeGenOpts() const { 221 return CGT.getCodeGenOpts(); 222 } 223 224 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); } 225 226 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 227 return false; 228 } 229 230 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 231 uint64_t Members) const { 232 return false; 233 } 234 235 LLVM_DUMP_METHOD void ABIArgInfo::dump() const { 236 raw_ostream &OS = llvm::errs(); 237 OS << "(ABIArgInfo Kind="; 238 switch (TheKind) { 239 case Direct: 240 OS << "Direct Type="; 241 if (llvm::Type *Ty = getCoerceToType()) 242 Ty->print(OS); 243 else 244 OS << "null"; 245 break; 246 case Extend: 247 OS << "Extend"; 248 break; 249 case Ignore: 250 OS << "Ignore"; 251 break; 252 case InAlloca: 253 OS << "InAlloca Offset=" << getInAllocaFieldIndex(); 254 break; 255 case Indirect: 256 OS << "Indirect Align=" << getIndirectAlign().getQuantity() 257 << " ByVal=" << getIndirectByVal() 258 << " Realign=" << getIndirectRealign(); 259 break; 260 case IndirectAliased: 261 OS << "Indirect Align=" << getIndirectAlign().getQuantity() 262 << " AadrSpace=" << getIndirectAddrSpace() 263 << " Realign=" << getIndirectRealign(); 264 break; 265 case Expand: 266 OS << "Expand"; 267 break; 268 case CoerceAndExpand: 269 OS << "CoerceAndExpand Type="; 270 getCoerceAndExpandType()->print(OS); 271 break; 272 } 273 OS << ")\n"; 274 } 275 276 // Dynamically round a pointer up to a multiple of the given alignment. 277 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF, 278 llvm::Value *Ptr, 279 CharUnits Align) { 280 llvm::Value *PtrAsInt = Ptr; 281 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align; 282 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy); 283 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt, 284 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1)); 285 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt, 286 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity())); 287 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt, 288 Ptr->getType(), 289 Ptr->getName() + ".aligned"); 290 return PtrAsInt; 291 } 292 293 /// Emit va_arg for a platform using the common void* representation, 294 /// where arguments are simply emitted in an array of slots on the stack. 295 /// 296 /// This version implements the core direct-value passing rules. 297 /// 298 /// \param SlotSize - The size and alignment of a stack slot. 299 /// Each argument will be allocated to a multiple of this number of 300 /// slots, and all the slots will be aligned to this value. 301 /// \param AllowHigherAlign - The slot alignment is not a cap; 302 /// an argument type with an alignment greater than the slot size 303 /// will be emitted on a higher-alignment address, potentially 304 /// leaving one or more empty slots behind as padding. If this 305 /// is false, the returned address might be less-aligned than 306 /// DirectAlign. 307 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF, 308 Address VAListAddr, 309 llvm::Type *DirectTy, 310 CharUnits DirectSize, 311 CharUnits DirectAlign, 312 CharUnits SlotSize, 313 bool AllowHigherAlign) { 314 // Cast the element type to i8* if necessary. Some platforms define 315 // va_list as a struct containing an i8* instead of just an i8*. 316 if (VAListAddr.getElementType() != CGF.Int8PtrTy) 317 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy); 318 319 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur"); 320 321 // If the CC aligns values higher than the slot size, do so if needed. 322 Address Addr = Address::invalid(); 323 if (AllowHigherAlign && DirectAlign > SlotSize) { 324 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign), 325 DirectAlign); 326 } else { 327 Addr = Address(Ptr, SlotSize); 328 } 329 330 // Advance the pointer past the argument, then store that back. 331 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize); 332 Address NextPtr = 333 CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next"); 334 CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 335 336 // If the argument is smaller than a slot, and this is a big-endian 337 // target, the argument will be right-adjusted in its slot. 338 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() && 339 !DirectTy->isStructTy()) { 340 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize); 341 } 342 343 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy); 344 return Addr; 345 } 346 347 /// Emit va_arg for a platform using the common void* representation, 348 /// where arguments are simply emitted in an array of slots on the stack. 349 /// 350 /// \param IsIndirect - Values of this type are passed indirectly. 351 /// \param ValueInfo - The size and alignment of this type, generally 352 /// computed with getContext().getTypeInfoInChars(ValueTy). 353 /// \param SlotSizeAndAlign - The size and alignment of a stack slot. 354 /// Each argument will be allocated to a multiple of this number of 355 /// slots, and all the slots will be aligned to this value. 356 /// \param AllowHigherAlign - The slot alignment is not a cap; 357 /// an argument type with an alignment greater than the slot size 358 /// will be emitted on a higher-alignment address, potentially 359 /// leaving one or more empty slots behind as padding. 360 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr, 361 QualType ValueTy, bool IsIndirect, 362 TypeInfoChars ValueInfo, 363 CharUnits SlotSizeAndAlign, 364 bool AllowHigherAlign) { 365 // The size and alignment of the value that was passed directly. 366 CharUnits DirectSize, DirectAlign; 367 if (IsIndirect) { 368 DirectSize = CGF.getPointerSize(); 369 DirectAlign = CGF.getPointerAlign(); 370 } else { 371 DirectSize = ValueInfo.Width; 372 DirectAlign = ValueInfo.Align; 373 } 374 375 // Cast the address we've calculated to the right type. 376 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy); 377 if (IsIndirect) 378 DirectTy = DirectTy->getPointerTo(0); 379 380 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy, 381 DirectSize, DirectAlign, 382 SlotSizeAndAlign, 383 AllowHigherAlign); 384 385 if (IsIndirect) { 386 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.Align); 387 } 388 389 return Addr; 390 391 } 392 393 static Address emitMergePHI(CodeGenFunction &CGF, 394 Address Addr1, llvm::BasicBlock *Block1, 395 Address Addr2, llvm::BasicBlock *Block2, 396 const llvm::Twine &Name = "") { 397 assert(Addr1.getType() == Addr2.getType()); 398 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name); 399 PHI->addIncoming(Addr1.getPointer(), Block1); 400 PHI->addIncoming(Addr2.getPointer(), Block2); 401 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment()); 402 return Address(PHI, Align); 403 } 404 405 TargetCodeGenInfo::~TargetCodeGenInfo() = default; 406 407 // If someone can figure out a general rule for this, that would be great. 408 // It's probably just doomed to be platform-dependent, though. 409 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const { 410 // Verified for: 411 // x86-64 FreeBSD, Linux, Darwin 412 // x86-32 FreeBSD, Linux, Darwin 413 // PowerPC Linux, Darwin 414 // ARM Darwin (*not* EABI) 415 // AArch64 Linux 416 return 32; 417 } 418 419 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args, 420 const FunctionNoProtoType *fnType) const { 421 // The following conventions are known to require this to be false: 422 // x86_stdcall 423 // MIPS 424 // For everything else, we just prefer false unless we opt out. 425 return false; 426 } 427 428 void 429 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib, 430 llvm::SmallString<24> &Opt) const { 431 // This assumes the user is passing a library name like "rt" instead of a 432 // filename like "librt.a/so", and that they don't care whether it's static or 433 // dynamic. 434 Opt = "-l"; 435 Opt += Lib; 436 } 437 438 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const { 439 // OpenCL kernels are called via an explicit runtime API with arguments 440 // set with clSetKernelArg(), not as normal sub-functions. 441 // Return SPIR_KERNEL by default as the kernel calling convention to 442 // ensure the fingerprint is fixed such way that each OpenCL argument 443 // gets one matching argument in the produced kernel function argument 444 // list to enable feasible implementation of clSetKernelArg() with 445 // aggregates etc. In case we would use the default C calling conv here, 446 // clSetKernelArg() might break depending on the target-specific 447 // conventions; different targets might split structs passed as values 448 // to multiple function arguments etc. 449 return llvm::CallingConv::SPIR_KERNEL; 450 } 451 452 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM, 453 llvm::PointerType *T, QualType QT) const { 454 return llvm::ConstantPointerNull::get(T); 455 } 456 457 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 458 const VarDecl *D) const { 459 assert(!CGM.getLangOpts().OpenCL && 460 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 461 "Address space agnostic languages only"); 462 return D ? D->getType().getAddressSpace() : LangAS::Default; 463 } 464 465 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast( 466 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr, 467 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const { 468 // Since target may map different address spaces in AST to the same address 469 // space, an address space conversion may end up as a bitcast. 470 if (auto *C = dyn_cast<llvm::Constant>(Src)) 471 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy); 472 // Try to preserve the source's name to make IR more readable. 473 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 474 Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : ""); 475 } 476 477 llvm::Constant * 478 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src, 479 LangAS SrcAddr, LangAS DestAddr, 480 llvm::Type *DestTy) const { 481 // Since target may map different address spaces in AST to the same address 482 // space, an address space conversion may end up as a bitcast. 483 return llvm::ConstantExpr::getPointerCast(Src, DestTy); 484 } 485 486 llvm::SyncScope::ID 487 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 488 SyncScope Scope, 489 llvm::AtomicOrdering Ordering, 490 llvm::LLVMContext &Ctx) const { 491 return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */ 492 } 493 494 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays); 495 496 /// isEmptyField - Return true iff a the field is "empty", that is it 497 /// is an unnamed bit-field or an (array of) empty record(s). 498 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD, 499 bool AllowArrays) { 500 if (FD->isUnnamedBitfield()) 501 return true; 502 503 QualType FT = FD->getType(); 504 505 // Constant arrays of empty records count as empty, strip them off. 506 // Constant arrays of zero length always count as empty. 507 bool WasArray = false; 508 if (AllowArrays) 509 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 510 if (AT->getSize() == 0) 511 return true; 512 FT = AT->getElementType(); 513 // The [[no_unique_address]] special case below does not apply to 514 // arrays of C++ empty records, so we need to remember this fact. 515 WasArray = true; 516 } 517 518 const RecordType *RT = FT->getAs<RecordType>(); 519 if (!RT) 520 return false; 521 522 // C++ record fields are never empty, at least in the Itanium ABI. 523 // 524 // FIXME: We should use a predicate for whether this behavior is true in the 525 // current ABI. 526 // 527 // The exception to the above rule are fields marked with the 528 // [[no_unique_address]] attribute (since C++20). Those do count as empty 529 // according to the Itanium ABI. The exception applies only to records, 530 // not arrays of records, so we must also check whether we stripped off an 531 // array type above. 532 if (isa<CXXRecordDecl>(RT->getDecl()) && 533 (WasArray || !FD->hasAttr<NoUniqueAddressAttr>())) 534 return false; 535 536 return isEmptyRecord(Context, FT, AllowArrays); 537 } 538 539 /// isEmptyRecord - Return true iff a structure contains only empty 540 /// fields. Note that a structure with a flexible array member is not 541 /// considered empty. 542 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) { 543 const RecordType *RT = T->getAs<RecordType>(); 544 if (!RT) 545 return false; 546 const RecordDecl *RD = RT->getDecl(); 547 if (RD->hasFlexibleArrayMember()) 548 return false; 549 550 // If this is a C++ record, check the bases first. 551 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 552 for (const auto &I : CXXRD->bases()) 553 if (!isEmptyRecord(Context, I.getType(), true)) 554 return false; 555 556 for (const auto *I : RD->fields()) 557 if (!isEmptyField(Context, I, AllowArrays)) 558 return false; 559 return true; 560 } 561 562 /// isSingleElementStruct - Determine if a structure is a "single 563 /// element struct", i.e. it has exactly one non-empty field or 564 /// exactly one field which is itself a single element 565 /// struct. Structures with flexible array members are never 566 /// considered single element structs. 567 /// 568 /// \return The field declaration for the single non-empty field, if 569 /// it exists. 570 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) { 571 const RecordType *RT = T->getAs<RecordType>(); 572 if (!RT) 573 return nullptr; 574 575 const RecordDecl *RD = RT->getDecl(); 576 if (RD->hasFlexibleArrayMember()) 577 return nullptr; 578 579 const Type *Found = nullptr; 580 581 // If this is a C++ record, check the bases first. 582 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 583 for (const auto &I : CXXRD->bases()) { 584 // Ignore empty records. 585 if (isEmptyRecord(Context, I.getType(), true)) 586 continue; 587 588 // If we already found an element then this isn't a single-element struct. 589 if (Found) 590 return nullptr; 591 592 // If this is non-empty and not a single element struct, the composite 593 // cannot be a single element struct. 594 Found = isSingleElementStruct(I.getType(), Context); 595 if (!Found) 596 return nullptr; 597 } 598 } 599 600 // Check for single element. 601 for (const auto *FD : RD->fields()) { 602 QualType FT = FD->getType(); 603 604 // Ignore empty fields. 605 if (isEmptyField(Context, FD, true)) 606 continue; 607 608 // If we already found an element then this isn't a single-element 609 // struct. 610 if (Found) 611 return nullptr; 612 613 // Treat single element arrays as the element. 614 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 615 if (AT->getSize().getZExtValue() != 1) 616 break; 617 FT = AT->getElementType(); 618 } 619 620 if (!isAggregateTypeForABI(FT)) { 621 Found = FT.getTypePtr(); 622 } else { 623 Found = isSingleElementStruct(FT, Context); 624 if (!Found) 625 return nullptr; 626 } 627 } 628 629 // We don't consider a struct a single-element struct if it has 630 // padding beyond the element type. 631 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T)) 632 return nullptr; 633 634 return Found; 635 } 636 637 namespace { 638 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty, 639 const ABIArgInfo &AI) { 640 // This default implementation defers to the llvm backend's va_arg 641 // instruction. It can handle only passing arguments directly 642 // (typically only handled in the backend for primitive types), or 643 // aggregates passed indirectly by pointer (NOTE: if the "byval" 644 // flag has ABI impact in the callee, this implementation cannot 645 // work.) 646 647 // Only a few cases are covered here at the moment -- those needed 648 // by the default abi. 649 llvm::Value *Val; 650 651 if (AI.isIndirect()) { 652 assert(!AI.getPaddingType() && 653 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 654 assert( 655 !AI.getIndirectRealign() && 656 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!"); 657 658 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty); 659 CharUnits TyAlignForABI = TyInfo.Align; 660 661 llvm::Type *BaseTy = 662 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 663 llvm::Value *Addr = 664 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy); 665 return Address(Addr, TyAlignForABI); 666 } else { 667 assert((AI.isDirect() || AI.isExtend()) && 668 "Unexpected ArgInfo Kind in generic VAArg emitter!"); 669 670 assert(!AI.getInReg() && 671 "Unexpected InReg seen in arginfo in generic VAArg emitter!"); 672 assert(!AI.getPaddingType() && 673 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 674 assert(!AI.getDirectOffset() && 675 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!"); 676 assert(!AI.getCoerceToType() && 677 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!"); 678 679 Address Temp = CGF.CreateMemTemp(Ty, "varet"); 680 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty)); 681 CGF.Builder.CreateStore(Val, Temp); 682 return Temp; 683 } 684 } 685 686 /// DefaultABIInfo - The default implementation for ABI specific 687 /// details. This implementation provides information which results in 688 /// self-consistent and sensible LLVM IR generation, but does not 689 /// conform to any particular ABI. 690 class DefaultABIInfo : public ABIInfo { 691 public: 692 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 693 694 ABIArgInfo classifyReturnType(QualType RetTy) const; 695 ABIArgInfo classifyArgumentType(QualType RetTy) const; 696 697 void computeInfo(CGFunctionInfo &FI) const override { 698 if (!getCXXABI().classifyReturnType(FI)) 699 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 700 for (auto &I : FI.arguments()) 701 I.info = classifyArgumentType(I.type); 702 } 703 704 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 705 QualType Ty) const override { 706 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 707 } 708 }; 709 710 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo { 711 public: 712 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 713 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 714 }; 715 716 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const { 717 Ty = useFirstFieldIfTransparentUnion(Ty); 718 719 if (isAggregateTypeForABI(Ty)) { 720 // Records with non-trivial destructors/copy-constructors should not be 721 // passed by value. 722 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 723 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 724 725 return getNaturalAlignIndirect(Ty); 726 } 727 728 // Treat an enum type as its underlying type. 729 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 730 Ty = EnumTy->getDecl()->getIntegerType(); 731 732 ASTContext &Context = getContext(); 733 if (const auto *EIT = Ty->getAs<ExtIntType>()) 734 if (EIT->getNumBits() > 735 Context.getTypeSize(Context.getTargetInfo().hasInt128Type() 736 ? Context.Int128Ty 737 : Context.LongLongTy)) 738 return getNaturalAlignIndirect(Ty); 739 740 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 741 : ABIArgInfo::getDirect()); 742 } 743 744 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const { 745 if (RetTy->isVoidType()) 746 return ABIArgInfo::getIgnore(); 747 748 if (isAggregateTypeForABI(RetTy)) 749 return getNaturalAlignIndirect(RetTy); 750 751 // Treat an enum type as its underlying type. 752 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 753 RetTy = EnumTy->getDecl()->getIntegerType(); 754 755 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 756 if (EIT->getNumBits() > 757 getContext().getTypeSize(getContext().getTargetInfo().hasInt128Type() 758 ? getContext().Int128Ty 759 : getContext().LongLongTy)) 760 return getNaturalAlignIndirect(RetTy); 761 762 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 763 : ABIArgInfo::getDirect()); 764 } 765 766 //===----------------------------------------------------------------------===// 767 // WebAssembly ABI Implementation 768 // 769 // This is a very simple ABI that relies a lot on DefaultABIInfo. 770 //===----------------------------------------------------------------------===// 771 772 class WebAssemblyABIInfo final : public SwiftABIInfo { 773 public: 774 enum ABIKind { 775 MVP = 0, 776 ExperimentalMV = 1, 777 }; 778 779 private: 780 DefaultABIInfo defaultInfo; 781 ABIKind Kind; 782 783 public: 784 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind) 785 : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {} 786 787 private: 788 ABIArgInfo classifyReturnType(QualType RetTy) const; 789 ABIArgInfo classifyArgumentType(QualType Ty) const; 790 791 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 792 // non-virtual, but computeInfo and EmitVAArg are virtual, so we 793 // overload them. 794 void computeInfo(CGFunctionInfo &FI) const override { 795 if (!getCXXABI().classifyReturnType(FI)) 796 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 797 for (auto &Arg : FI.arguments()) 798 Arg.info = classifyArgumentType(Arg.type); 799 } 800 801 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 802 QualType Ty) const override; 803 804 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 805 bool asReturnValue) const override { 806 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 807 } 808 809 bool isSwiftErrorInRegister() const override { 810 return false; 811 } 812 }; 813 814 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo { 815 public: 816 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 817 WebAssemblyABIInfo::ABIKind K) 818 : TargetCodeGenInfo(std::make_unique<WebAssemblyABIInfo>(CGT, K)) {} 819 820 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 821 CodeGen::CodeGenModule &CGM) const override { 822 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 823 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 824 if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) { 825 llvm::Function *Fn = cast<llvm::Function>(GV); 826 llvm::AttrBuilder B; 827 B.addAttribute("wasm-import-module", Attr->getImportModule()); 828 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 829 } 830 if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) { 831 llvm::Function *Fn = cast<llvm::Function>(GV); 832 llvm::AttrBuilder B; 833 B.addAttribute("wasm-import-name", Attr->getImportName()); 834 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 835 } 836 if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) { 837 llvm::Function *Fn = cast<llvm::Function>(GV); 838 llvm::AttrBuilder B; 839 B.addAttribute("wasm-export-name", Attr->getExportName()); 840 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 841 } 842 } 843 844 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 845 llvm::Function *Fn = cast<llvm::Function>(GV); 846 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype()) 847 Fn->addFnAttr("no-prototype"); 848 } 849 } 850 }; 851 852 /// Classify argument of given type \p Ty. 853 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const { 854 Ty = useFirstFieldIfTransparentUnion(Ty); 855 856 if (isAggregateTypeForABI(Ty)) { 857 // Records with non-trivial destructors/copy-constructors should not be 858 // passed by value. 859 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 860 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 861 // Ignore empty structs/unions. 862 if (isEmptyRecord(getContext(), Ty, true)) 863 return ABIArgInfo::getIgnore(); 864 // Lower single-element structs to just pass a regular value. TODO: We 865 // could do reasonable-size multiple-element structs too, using getExpand(), 866 // though watch out for things like bitfields. 867 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 868 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 869 // For the experimental multivalue ABI, fully expand all other aggregates 870 if (Kind == ABIKind::ExperimentalMV) { 871 const RecordType *RT = Ty->getAs<RecordType>(); 872 assert(RT); 873 bool HasBitField = false; 874 for (auto *Field : RT->getDecl()->fields()) { 875 if (Field->isBitField()) { 876 HasBitField = true; 877 break; 878 } 879 } 880 if (!HasBitField) 881 return ABIArgInfo::getExpand(); 882 } 883 } 884 885 // Otherwise just do the default thing. 886 return defaultInfo.classifyArgumentType(Ty); 887 } 888 889 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const { 890 if (isAggregateTypeForABI(RetTy)) { 891 // Records with non-trivial destructors/copy-constructors should not be 892 // returned by value. 893 if (!getRecordArgABI(RetTy, getCXXABI())) { 894 // Ignore empty structs/unions. 895 if (isEmptyRecord(getContext(), RetTy, true)) 896 return ABIArgInfo::getIgnore(); 897 // Lower single-element structs to just return a regular value. TODO: We 898 // could do reasonable-size multiple-element structs too, using 899 // ABIArgInfo::getDirect(). 900 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 901 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 902 // For the experimental multivalue ABI, return all other aggregates 903 if (Kind == ABIKind::ExperimentalMV) 904 return ABIArgInfo::getDirect(); 905 } 906 } 907 908 // Otherwise just do the default thing. 909 return defaultInfo.classifyReturnType(RetTy); 910 } 911 912 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 913 QualType Ty) const { 914 bool IsIndirect = isAggregateTypeForABI(Ty) && 915 !isEmptyRecord(getContext(), Ty, true) && 916 !isSingleElementStruct(Ty, getContext()); 917 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 918 getContext().getTypeInfoInChars(Ty), 919 CharUnits::fromQuantity(4), 920 /*AllowHigherAlign=*/true); 921 } 922 923 //===----------------------------------------------------------------------===// 924 // le32/PNaCl bitcode ABI Implementation 925 // 926 // This is a simplified version of the x86_32 ABI. Arguments and return values 927 // are always passed on the stack. 928 //===----------------------------------------------------------------------===// 929 930 class PNaClABIInfo : public ABIInfo { 931 public: 932 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 933 934 ABIArgInfo classifyReturnType(QualType RetTy) const; 935 ABIArgInfo classifyArgumentType(QualType RetTy) const; 936 937 void computeInfo(CGFunctionInfo &FI) const override; 938 Address EmitVAArg(CodeGenFunction &CGF, 939 Address VAListAddr, QualType Ty) const override; 940 }; 941 942 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo { 943 public: 944 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 945 : TargetCodeGenInfo(std::make_unique<PNaClABIInfo>(CGT)) {} 946 }; 947 948 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const { 949 if (!getCXXABI().classifyReturnType(FI)) 950 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 951 952 for (auto &I : FI.arguments()) 953 I.info = classifyArgumentType(I.type); 954 } 955 956 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 957 QualType Ty) const { 958 // The PNaCL ABI is a bit odd, in that varargs don't use normal 959 // function classification. Structs get passed directly for varargs 960 // functions, through a rewriting transform in 961 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows 962 // this target to actually support a va_arg instructions with an 963 // aggregate type, unlike other targets. 964 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 965 } 966 967 /// Classify argument of given type \p Ty. 968 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const { 969 if (isAggregateTypeForABI(Ty)) { 970 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 971 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 972 return getNaturalAlignIndirect(Ty); 973 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 974 // Treat an enum type as its underlying type. 975 Ty = EnumTy->getDecl()->getIntegerType(); 976 } else if (Ty->isFloatingType()) { 977 // Floating-point types don't go inreg. 978 return ABIArgInfo::getDirect(); 979 } else if (const auto *EIT = Ty->getAs<ExtIntType>()) { 980 // Treat extended integers as integers if <=64, otherwise pass indirectly. 981 if (EIT->getNumBits() > 64) 982 return getNaturalAlignIndirect(Ty); 983 return ABIArgInfo::getDirect(); 984 } 985 986 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 987 : ABIArgInfo::getDirect()); 988 } 989 990 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const { 991 if (RetTy->isVoidType()) 992 return ABIArgInfo::getIgnore(); 993 994 // In the PNaCl ABI we always return records/structures on the stack. 995 if (isAggregateTypeForABI(RetTy)) 996 return getNaturalAlignIndirect(RetTy); 997 998 // Treat extended integers as integers if <=64, otherwise pass indirectly. 999 if (const auto *EIT = RetTy->getAs<ExtIntType>()) { 1000 if (EIT->getNumBits() > 64) 1001 return getNaturalAlignIndirect(RetTy); 1002 return ABIArgInfo::getDirect(); 1003 } 1004 1005 // Treat an enum type as its underlying type. 1006 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1007 RetTy = EnumTy->getDecl()->getIntegerType(); 1008 1009 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 1010 : ABIArgInfo::getDirect()); 1011 } 1012 1013 /// IsX86_MMXType - Return true if this is an MMX type. 1014 bool IsX86_MMXType(llvm::Type *IRType) { 1015 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>. 1016 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 && 1017 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() && 1018 IRType->getScalarSizeInBits() != 64; 1019 } 1020 1021 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1022 StringRef Constraint, 1023 llvm::Type* Ty) { 1024 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint) 1025 .Cases("y", "&y", "^Ym", true) 1026 .Default(false); 1027 if (IsMMXCons && Ty->isVectorTy()) { 1028 if (cast<llvm::VectorType>(Ty)->getPrimitiveSizeInBits().getFixedSize() != 1029 64) { 1030 // Invalid MMX constraint 1031 return nullptr; 1032 } 1033 1034 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); 1035 } 1036 1037 // No operation needed 1038 return Ty; 1039 } 1040 1041 /// Returns true if this type can be passed in SSE registers with the 1042 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64. 1043 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) { 1044 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 1045 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) { 1046 if (BT->getKind() == BuiltinType::LongDouble) { 1047 if (&Context.getTargetInfo().getLongDoubleFormat() == 1048 &llvm::APFloat::x87DoubleExtended()) 1049 return false; 1050 } 1051 return true; 1052 } 1053 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 1054 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX 1055 // registers specially. 1056 unsigned VecSize = Context.getTypeSize(VT); 1057 if (VecSize == 128 || VecSize == 256 || VecSize == 512) 1058 return true; 1059 } 1060 return false; 1061 } 1062 1063 /// Returns true if this aggregate is small enough to be passed in SSE registers 1064 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64. 1065 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) { 1066 return NumMembers <= 4; 1067 } 1068 1069 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86. 1070 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) { 1071 auto AI = ABIArgInfo::getDirect(T); 1072 AI.setInReg(true); 1073 AI.setCanBeFlattened(false); 1074 return AI; 1075 } 1076 1077 //===----------------------------------------------------------------------===// 1078 // X86-32 ABI Implementation 1079 //===----------------------------------------------------------------------===// 1080 1081 /// Similar to llvm::CCState, but for Clang. 1082 struct CCState { 1083 CCState(CGFunctionInfo &FI) 1084 : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {} 1085 1086 llvm::SmallBitVector IsPreassigned; 1087 unsigned CC = CallingConv::CC_C; 1088 unsigned FreeRegs = 0; 1089 unsigned FreeSSERegs = 0; 1090 }; 1091 1092 enum { 1093 // Vectorcall only allows the first 6 parameters to be passed in registers. 1094 VectorcallMaxParamNumAsReg = 6 1095 }; 1096 1097 /// X86_32ABIInfo - The X86-32 ABI information. 1098 class X86_32ABIInfo : public SwiftABIInfo { 1099 enum Class { 1100 Integer, 1101 Float 1102 }; 1103 1104 static const unsigned MinABIStackAlignInBytes = 4; 1105 1106 bool IsDarwinVectorABI; 1107 bool IsRetSmallStructInRegABI; 1108 bool IsWin32StructABI; 1109 bool IsSoftFloatABI; 1110 bool IsMCUABI; 1111 unsigned DefaultNumRegisterParameters; 1112 1113 static bool isRegisterSize(unsigned Size) { 1114 return (Size == 8 || Size == 16 || Size == 32 || Size == 64); 1115 } 1116 1117 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 1118 // FIXME: Assumes vectorcall is in use. 1119 return isX86VectorTypeForVectorCall(getContext(), Ty); 1120 } 1121 1122 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 1123 uint64_t NumMembers) const override { 1124 // FIXME: Assumes vectorcall is in use. 1125 return isX86VectorCallAggregateSmallEnough(NumMembers); 1126 } 1127 1128 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const; 1129 1130 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1131 /// such that the argument will be passed in memory. 1132 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 1133 1134 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const; 1135 1136 /// Return the alignment to use for the given type on the stack. 1137 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; 1138 1139 Class classify(QualType Ty) const; 1140 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; 1141 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 1142 1143 /// Updates the number of available free registers, returns 1144 /// true if any registers were allocated. 1145 bool updateFreeRegs(QualType Ty, CCState &State) const; 1146 1147 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg, 1148 bool &NeedsPadding) const; 1149 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const; 1150 1151 bool canExpandIndirectArgument(QualType Ty) const; 1152 1153 /// Rewrite the function info so that all memory arguments use 1154 /// inalloca. 1155 void rewriteWithInAlloca(CGFunctionInfo &FI) const; 1156 1157 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1158 CharUnits &StackOffset, ABIArgInfo &Info, 1159 QualType Type) const; 1160 void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const; 1161 1162 public: 1163 1164 void computeInfo(CGFunctionInfo &FI) const override; 1165 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 1166 QualType Ty) const override; 1167 1168 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1169 bool RetSmallStructInRegABI, bool Win32StructABI, 1170 unsigned NumRegisterParameters, bool SoftFloatABI) 1171 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI), 1172 IsRetSmallStructInRegABI(RetSmallStructInRegABI), 1173 IsWin32StructABI(Win32StructABI), 1174 IsSoftFloatABI(SoftFloatABI), 1175 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()), 1176 DefaultNumRegisterParameters(NumRegisterParameters) {} 1177 1178 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 1179 bool asReturnValue) const override { 1180 // LLVM's x86-32 lowering currently only assigns up to three 1181 // integer registers and three fp registers. Oddly, it'll use up to 1182 // four vector registers for vectors, but those can overlap with the 1183 // scalar registers. 1184 return occupiesMoreThan(CGT, scalars, /*total*/ 3); 1185 } 1186 1187 bool isSwiftErrorInRegister() const override { 1188 // x86-32 lowering does not support passing swifterror in a register. 1189 return false; 1190 } 1191 }; 1192 1193 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { 1194 public: 1195 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1196 bool RetSmallStructInRegABI, bool Win32StructABI, 1197 unsigned NumRegisterParameters, bool SoftFloatABI) 1198 : TargetCodeGenInfo(std::make_unique<X86_32ABIInfo>( 1199 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI, 1200 NumRegisterParameters, SoftFloatABI)) {} 1201 1202 static bool isStructReturnInRegABI( 1203 const llvm::Triple &Triple, const CodeGenOptions &Opts); 1204 1205 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 1206 CodeGen::CodeGenModule &CGM) const override; 1207 1208 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 1209 // Darwin uses different dwarf register numbers for EH. 1210 if (CGM.getTarget().getTriple().isOSDarwin()) return 5; 1211 return 4; 1212 } 1213 1214 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1215 llvm::Value *Address) const override; 1216 1217 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1218 StringRef Constraint, 1219 llvm::Type* Ty) const override { 1220 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 1221 } 1222 1223 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue, 1224 std::string &Constraints, 1225 std::vector<llvm::Type *> &ResultRegTypes, 1226 std::vector<llvm::Type *> &ResultTruncRegTypes, 1227 std::vector<LValue> &ResultRegDests, 1228 std::string &AsmString, 1229 unsigned NumOutputs) const override; 1230 1231 llvm::Constant * 1232 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 1233 unsigned Sig = (0xeb << 0) | // jmp rel8 1234 (0x06 << 8) | // .+0x08 1235 ('v' << 16) | 1236 ('2' << 24); 1237 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 1238 } 1239 1240 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 1241 return "movl\t%ebp, %ebp" 1242 "\t\t// marker for objc_retainAutoreleaseReturnValue"; 1243 } 1244 }; 1245 1246 } 1247 1248 /// Rewrite input constraint references after adding some output constraints. 1249 /// In the case where there is one output and one input and we add one output, 1250 /// we need to replace all operand references greater than or equal to 1: 1251 /// mov $0, $1 1252 /// mov eax, $1 1253 /// The result will be: 1254 /// mov $0, $2 1255 /// mov eax, $2 1256 static void rewriteInputConstraintReferences(unsigned FirstIn, 1257 unsigned NumNewOuts, 1258 std::string &AsmString) { 1259 std::string Buf; 1260 llvm::raw_string_ostream OS(Buf); 1261 size_t Pos = 0; 1262 while (Pos < AsmString.size()) { 1263 size_t DollarStart = AsmString.find('$', Pos); 1264 if (DollarStart == std::string::npos) 1265 DollarStart = AsmString.size(); 1266 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart); 1267 if (DollarEnd == std::string::npos) 1268 DollarEnd = AsmString.size(); 1269 OS << StringRef(&AsmString[Pos], DollarEnd - Pos); 1270 Pos = DollarEnd; 1271 size_t NumDollars = DollarEnd - DollarStart; 1272 if (NumDollars % 2 != 0 && Pos < AsmString.size()) { 1273 // We have an operand reference. 1274 size_t DigitStart = Pos; 1275 if (AsmString[DigitStart] == '{') { 1276 OS << '{'; 1277 ++DigitStart; 1278 } 1279 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart); 1280 if (DigitEnd == std::string::npos) 1281 DigitEnd = AsmString.size(); 1282 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart); 1283 unsigned OperandIndex; 1284 if (!OperandStr.getAsInteger(10, OperandIndex)) { 1285 if (OperandIndex >= FirstIn) 1286 OperandIndex += NumNewOuts; 1287 OS << OperandIndex; 1288 } else { 1289 OS << OperandStr; 1290 } 1291 Pos = DigitEnd; 1292 } 1293 } 1294 AsmString = std::move(OS.str()); 1295 } 1296 1297 /// Add output constraints for EAX:EDX because they are return registers. 1298 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs( 1299 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints, 1300 std::vector<llvm::Type *> &ResultRegTypes, 1301 std::vector<llvm::Type *> &ResultTruncRegTypes, 1302 std::vector<LValue> &ResultRegDests, std::string &AsmString, 1303 unsigned NumOutputs) const { 1304 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType()); 1305 1306 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is 1307 // larger. 1308 if (!Constraints.empty()) 1309 Constraints += ','; 1310 if (RetWidth <= 32) { 1311 Constraints += "={eax}"; 1312 ResultRegTypes.push_back(CGF.Int32Ty); 1313 } else { 1314 // Use the 'A' constraint for EAX:EDX. 1315 Constraints += "=A"; 1316 ResultRegTypes.push_back(CGF.Int64Ty); 1317 } 1318 1319 // Truncate EAX or EAX:EDX to an integer of the appropriate size. 1320 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth); 1321 ResultTruncRegTypes.push_back(CoerceTy); 1322 1323 // Coerce the integer by bitcasting the return slot pointer. 1324 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF), 1325 CoerceTy->getPointerTo())); 1326 ResultRegDests.push_back(ReturnSlot); 1327 1328 rewriteInputConstraintReferences(NumOutputs, 1, AsmString); 1329 } 1330 1331 /// shouldReturnTypeInRegister - Determine if the given type should be 1332 /// returned in a register (for the Darwin and MCU ABI). 1333 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, 1334 ASTContext &Context) const { 1335 uint64_t Size = Context.getTypeSize(Ty); 1336 1337 // For i386, type must be register sized. 1338 // For the MCU ABI, it only needs to be <= 8-byte 1339 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size))) 1340 return false; 1341 1342 if (Ty->isVectorType()) { 1343 // 64- and 128- bit vectors inside structures are not returned in 1344 // registers. 1345 if (Size == 64 || Size == 128) 1346 return false; 1347 1348 return true; 1349 } 1350 1351 // If this is a builtin, pointer, enum, complex type, member pointer, or 1352 // member function pointer it is ok. 1353 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() || 1354 Ty->isAnyComplexType() || Ty->isEnumeralType() || 1355 Ty->isBlockPointerType() || Ty->isMemberPointerType()) 1356 return true; 1357 1358 // Arrays are treated like records. 1359 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) 1360 return shouldReturnTypeInRegister(AT->getElementType(), Context); 1361 1362 // Otherwise, it must be a record type. 1363 const RecordType *RT = Ty->getAs<RecordType>(); 1364 if (!RT) return false; 1365 1366 // FIXME: Traverse bases here too. 1367 1368 // Structure types are passed in register if all fields would be 1369 // passed in a register. 1370 for (const auto *FD : RT->getDecl()->fields()) { 1371 // Empty fields are ignored. 1372 if (isEmptyField(Context, FD, true)) 1373 continue; 1374 1375 // Check fields recursively. 1376 if (!shouldReturnTypeInRegister(FD->getType(), Context)) 1377 return false; 1378 } 1379 return true; 1380 } 1381 1382 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { 1383 // Treat complex types as the element type. 1384 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 1385 Ty = CTy->getElementType(); 1386 1387 // Check for a type which we know has a simple scalar argument-passing 1388 // convention without any padding. (We're specifically looking for 32 1389 // and 64-bit integer and integer-equivalents, float, and double.) 1390 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() && 1391 !Ty->isEnumeralType() && !Ty->isBlockPointerType()) 1392 return false; 1393 1394 uint64_t Size = Context.getTypeSize(Ty); 1395 return Size == 32 || Size == 64; 1396 } 1397 1398 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD, 1399 uint64_t &Size) { 1400 for (const auto *FD : RD->fields()) { 1401 // Scalar arguments on the stack get 4 byte alignment on x86. If the 1402 // argument is smaller than 32-bits, expanding the struct will create 1403 // alignment padding. 1404 if (!is32Or64BitBasicType(FD->getType(), Context)) 1405 return false; 1406 1407 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know 1408 // how to expand them yet, and the predicate for telling if a bitfield still 1409 // counts as "basic" is more complicated than what we were doing previously. 1410 if (FD->isBitField()) 1411 return false; 1412 1413 Size += Context.getTypeSize(FD->getType()); 1414 } 1415 return true; 1416 } 1417 1418 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD, 1419 uint64_t &Size) { 1420 // Don't do this if there are any non-empty bases. 1421 for (const CXXBaseSpecifier &Base : RD->bases()) { 1422 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(), 1423 Size)) 1424 return false; 1425 } 1426 if (!addFieldSizes(Context, RD, Size)) 1427 return false; 1428 return true; 1429 } 1430 1431 /// Test whether an argument type which is to be passed indirectly (on the 1432 /// stack) would have the equivalent layout if it was expanded into separate 1433 /// arguments. If so, we prefer to do the latter to avoid inhibiting 1434 /// optimizations. 1435 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const { 1436 // We can only expand structure types. 1437 const RecordType *RT = Ty->getAs<RecordType>(); 1438 if (!RT) 1439 return false; 1440 const RecordDecl *RD = RT->getDecl(); 1441 uint64_t Size = 0; 1442 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1443 if (!IsWin32StructABI) { 1444 // On non-Windows, we have to conservatively match our old bitcode 1445 // prototypes in order to be ABI-compatible at the bitcode level. 1446 if (!CXXRD->isCLike()) 1447 return false; 1448 } else { 1449 // Don't do this for dynamic classes. 1450 if (CXXRD->isDynamicClass()) 1451 return false; 1452 } 1453 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size)) 1454 return false; 1455 } else { 1456 if (!addFieldSizes(getContext(), RD, Size)) 1457 return false; 1458 } 1459 1460 // We can do this if there was no alignment padding. 1461 return Size == getContext().getTypeSize(Ty); 1462 } 1463 1464 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const { 1465 // If the return value is indirect, then the hidden argument is consuming one 1466 // integer register. 1467 if (State.FreeRegs) { 1468 --State.FreeRegs; 1469 if (!IsMCUABI) 1470 return getNaturalAlignIndirectInReg(RetTy); 1471 } 1472 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 1473 } 1474 1475 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, 1476 CCState &State) const { 1477 if (RetTy->isVoidType()) 1478 return ABIArgInfo::getIgnore(); 1479 1480 const Type *Base = nullptr; 1481 uint64_t NumElts = 0; 1482 if ((State.CC == llvm::CallingConv::X86_VectorCall || 1483 State.CC == llvm::CallingConv::X86_RegCall) && 1484 isHomogeneousAggregate(RetTy, Base, NumElts)) { 1485 // The LLVM struct type for such an aggregate should lower properly. 1486 return ABIArgInfo::getDirect(); 1487 } 1488 1489 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 1490 // On Darwin, some vectors are returned in registers. 1491 if (IsDarwinVectorABI) { 1492 uint64_t Size = getContext().getTypeSize(RetTy); 1493 1494 // 128-bit vectors are a special case; they are returned in 1495 // registers and we need to make sure to pick a type the LLVM 1496 // backend will like. 1497 if (Size == 128) 1498 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 1499 llvm::Type::getInt64Ty(getVMContext()), 2)); 1500 1501 // Always return in register if it fits in a general purpose 1502 // register, or if it is 64 bits and has a single element. 1503 if ((Size == 8 || Size == 16 || Size == 32) || 1504 (Size == 64 && VT->getNumElements() == 1)) 1505 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 1506 Size)); 1507 1508 return getIndirectReturnResult(RetTy, State); 1509 } 1510 1511 return ABIArgInfo::getDirect(); 1512 } 1513 1514 if (isAggregateTypeForABI(RetTy)) { 1515 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 1516 // Structures with flexible arrays are always indirect. 1517 if (RT->getDecl()->hasFlexibleArrayMember()) 1518 return getIndirectReturnResult(RetTy, State); 1519 } 1520 1521 // If specified, structs and unions are always indirect. 1522 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType()) 1523 return getIndirectReturnResult(RetTy, State); 1524 1525 // Ignore empty structs/unions. 1526 if (isEmptyRecord(getContext(), RetTy, true)) 1527 return ABIArgInfo::getIgnore(); 1528 1529 // Small structures which are register sized are generally returned 1530 // in a register. 1531 if (shouldReturnTypeInRegister(RetTy, getContext())) { 1532 uint64_t Size = getContext().getTypeSize(RetTy); 1533 1534 // As a special-case, if the struct is a "single-element" struct, and 1535 // the field is of type "float" or "double", return it in a 1536 // floating-point register. (MSVC does not apply this special case.) 1537 // We apply a similar transformation for pointer types to improve the 1538 // quality of the generated IR. 1539 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 1540 if ((!IsWin32StructABI && SeltTy->isRealFloatingType()) 1541 || SeltTy->hasPointerRepresentation()) 1542 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 1543 1544 // FIXME: We should be able to narrow this integer in cases with dead 1545 // padding. 1546 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); 1547 } 1548 1549 return getIndirectReturnResult(RetTy, State); 1550 } 1551 1552 // Treat an enum type as its underlying type. 1553 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1554 RetTy = EnumTy->getDecl()->getIntegerType(); 1555 1556 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 1557 if (EIT->getNumBits() > 64) 1558 return getIndirectReturnResult(RetTy, State); 1559 1560 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 1561 : ABIArgInfo::getDirect()); 1562 } 1563 1564 static bool isSIMDVectorType(ASTContext &Context, QualType Ty) { 1565 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128; 1566 } 1567 1568 static bool isRecordWithSIMDVectorType(ASTContext &Context, QualType Ty) { 1569 const RecordType *RT = Ty->getAs<RecordType>(); 1570 if (!RT) 1571 return 0; 1572 const RecordDecl *RD = RT->getDecl(); 1573 1574 // If this is a C++ record, check the bases first. 1575 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1576 for (const auto &I : CXXRD->bases()) 1577 if (!isRecordWithSIMDVectorType(Context, I.getType())) 1578 return false; 1579 1580 for (const auto *i : RD->fields()) { 1581 QualType FT = i->getType(); 1582 1583 if (isSIMDVectorType(Context, FT)) 1584 return true; 1585 1586 if (isRecordWithSIMDVectorType(Context, FT)) 1587 return true; 1588 } 1589 1590 return false; 1591 } 1592 1593 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, 1594 unsigned Align) const { 1595 // Otherwise, if the alignment is less than or equal to the minimum ABI 1596 // alignment, just use the default; the backend will handle this. 1597 if (Align <= MinABIStackAlignInBytes) 1598 return 0; // Use default alignment. 1599 1600 // On non-Darwin, the stack type alignment is always 4. 1601 if (!IsDarwinVectorABI) { 1602 // Set explicit alignment, since we may need to realign the top. 1603 return MinABIStackAlignInBytes; 1604 } 1605 1606 // Otherwise, if the type contains an SSE vector type, the alignment is 16. 1607 if (Align >= 16 && (isSIMDVectorType(getContext(), Ty) || 1608 isRecordWithSIMDVectorType(getContext(), Ty))) 1609 return 16; 1610 1611 return MinABIStackAlignInBytes; 1612 } 1613 1614 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal, 1615 CCState &State) const { 1616 if (!ByVal) { 1617 if (State.FreeRegs) { 1618 --State.FreeRegs; // Non-byval indirects just use one pointer. 1619 if (!IsMCUABI) 1620 return getNaturalAlignIndirectInReg(Ty); 1621 } 1622 return getNaturalAlignIndirect(Ty, false); 1623 } 1624 1625 // Compute the byval alignment. 1626 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 1627 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); 1628 if (StackAlign == 0) 1629 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true); 1630 1631 // If the stack alignment is less than the type alignment, realign the 1632 // argument. 1633 bool Realign = TypeAlign > StackAlign; 1634 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign), 1635 /*ByVal=*/true, Realign); 1636 } 1637 1638 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const { 1639 const Type *T = isSingleElementStruct(Ty, getContext()); 1640 if (!T) 1641 T = Ty.getTypePtr(); 1642 1643 if (const BuiltinType *BT = T->getAs<BuiltinType>()) { 1644 BuiltinType::Kind K = BT->getKind(); 1645 if (K == BuiltinType::Float || K == BuiltinType::Double) 1646 return Float; 1647 } 1648 return Integer; 1649 } 1650 1651 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const { 1652 if (!IsSoftFloatABI) { 1653 Class C = classify(Ty); 1654 if (C == Float) 1655 return false; 1656 } 1657 1658 unsigned Size = getContext().getTypeSize(Ty); 1659 unsigned SizeInRegs = (Size + 31) / 32; 1660 1661 if (SizeInRegs == 0) 1662 return false; 1663 1664 if (!IsMCUABI) { 1665 if (SizeInRegs > State.FreeRegs) { 1666 State.FreeRegs = 0; 1667 return false; 1668 } 1669 } else { 1670 // The MCU psABI allows passing parameters in-reg even if there are 1671 // earlier parameters that are passed on the stack. Also, 1672 // it does not allow passing >8-byte structs in-register, 1673 // even if there are 3 free registers available. 1674 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2) 1675 return false; 1676 } 1677 1678 State.FreeRegs -= SizeInRegs; 1679 return true; 1680 } 1681 1682 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State, 1683 bool &InReg, 1684 bool &NeedsPadding) const { 1685 // On Windows, aggregates other than HFAs are never passed in registers, and 1686 // they do not consume register slots. Homogenous floating-point aggregates 1687 // (HFAs) have already been dealt with at this point. 1688 if (IsWin32StructABI && isAggregateTypeForABI(Ty)) 1689 return false; 1690 1691 NeedsPadding = false; 1692 InReg = !IsMCUABI; 1693 1694 if (!updateFreeRegs(Ty, State)) 1695 return false; 1696 1697 if (IsMCUABI) 1698 return true; 1699 1700 if (State.CC == llvm::CallingConv::X86_FastCall || 1701 State.CC == llvm::CallingConv::X86_VectorCall || 1702 State.CC == llvm::CallingConv::X86_RegCall) { 1703 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs) 1704 NeedsPadding = true; 1705 1706 return false; 1707 } 1708 1709 return true; 1710 } 1711 1712 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const { 1713 if (!updateFreeRegs(Ty, State)) 1714 return false; 1715 1716 if (IsMCUABI) 1717 return false; 1718 1719 if (State.CC == llvm::CallingConv::X86_FastCall || 1720 State.CC == llvm::CallingConv::X86_VectorCall || 1721 State.CC == llvm::CallingConv::X86_RegCall) { 1722 if (getContext().getTypeSize(Ty) > 32) 1723 return false; 1724 1725 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() || 1726 Ty->isReferenceType()); 1727 } 1728 1729 return true; 1730 } 1731 1732 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const { 1733 // Vectorcall x86 works subtly different than in x64, so the format is 1734 // a bit different than the x64 version. First, all vector types (not HVAs) 1735 // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers. 1736 // This differs from the x64 implementation, where the first 6 by INDEX get 1737 // registers. 1738 // In the second pass over the arguments, HVAs are passed in the remaining 1739 // vector registers if possible, or indirectly by address. The address will be 1740 // passed in ECX/EDX if available. Any other arguments are passed according to 1741 // the usual fastcall rules. 1742 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1743 for (int I = 0, E = Args.size(); I < E; ++I) { 1744 const Type *Base = nullptr; 1745 uint64_t NumElts = 0; 1746 const QualType &Ty = Args[I].type; 1747 if ((Ty->isVectorType() || Ty->isBuiltinType()) && 1748 isHomogeneousAggregate(Ty, Base, NumElts)) { 1749 if (State.FreeSSERegs >= NumElts) { 1750 State.FreeSSERegs -= NumElts; 1751 Args[I].info = ABIArgInfo::getDirectInReg(); 1752 State.IsPreassigned.set(I); 1753 } 1754 } 1755 } 1756 } 1757 1758 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, 1759 CCState &State) const { 1760 // FIXME: Set alignment on indirect arguments. 1761 bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall; 1762 bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall; 1763 bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall; 1764 1765 Ty = useFirstFieldIfTransparentUnion(Ty); 1766 TypeInfo TI = getContext().getTypeInfo(Ty); 1767 1768 // Check with the C++ ABI first. 1769 const RecordType *RT = Ty->getAs<RecordType>(); 1770 if (RT) { 1771 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 1772 if (RAA == CGCXXABI::RAA_Indirect) { 1773 return getIndirectResult(Ty, false, State); 1774 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 1775 // The field index doesn't matter, we'll fix it up later. 1776 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0); 1777 } 1778 } 1779 1780 // Regcall uses the concept of a homogenous vector aggregate, similar 1781 // to other targets. 1782 const Type *Base = nullptr; 1783 uint64_t NumElts = 0; 1784 if ((IsRegCall || IsVectorCall) && 1785 isHomogeneousAggregate(Ty, Base, NumElts)) { 1786 if (State.FreeSSERegs >= NumElts) { 1787 State.FreeSSERegs -= NumElts; 1788 1789 // Vectorcall passes HVAs directly and does not flatten them, but regcall 1790 // does. 1791 if (IsVectorCall) 1792 return getDirectX86Hva(); 1793 1794 if (Ty->isBuiltinType() || Ty->isVectorType()) 1795 return ABIArgInfo::getDirect(); 1796 return ABIArgInfo::getExpand(); 1797 } 1798 return getIndirectResult(Ty, /*ByVal=*/false, State); 1799 } 1800 1801 if (isAggregateTypeForABI(Ty)) { 1802 // Structures with flexible arrays are always indirect. 1803 // FIXME: This should not be byval! 1804 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 1805 return getIndirectResult(Ty, true, State); 1806 1807 // Ignore empty structs/unions on non-Windows. 1808 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true)) 1809 return ABIArgInfo::getIgnore(); 1810 1811 llvm::LLVMContext &LLVMContext = getVMContext(); 1812 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 1813 bool NeedsPadding = false; 1814 bool InReg; 1815 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) { 1816 unsigned SizeInRegs = (TI.Width + 31) / 32; 1817 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32); 1818 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 1819 if (InReg) 1820 return ABIArgInfo::getDirectInReg(Result); 1821 else 1822 return ABIArgInfo::getDirect(Result); 1823 } 1824 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr; 1825 1826 // Pass over-aligned aggregates on Windows indirectly. This behavior was 1827 // added in MSVC 2015. 1828 if (IsWin32StructABI && TI.AlignIsRequired && TI.Align > 32) 1829 return getIndirectResult(Ty, /*ByVal=*/false, State); 1830 1831 // Expand small (<= 128-bit) record types when we know that the stack layout 1832 // of those arguments will match the struct. This is important because the 1833 // LLVM backend isn't smart enough to remove byval, which inhibits many 1834 // optimizations. 1835 // Don't do this for the MCU if there are still free integer registers 1836 // (see X86_64 ABI for full explanation). 1837 if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) && 1838 canExpandIndirectArgument(Ty)) 1839 return ABIArgInfo::getExpandWithPadding( 1840 IsFastCall || IsVectorCall || IsRegCall, PaddingType); 1841 1842 return getIndirectResult(Ty, true, State); 1843 } 1844 1845 if (const VectorType *VT = Ty->getAs<VectorType>()) { 1846 // On Windows, vectors are passed directly if registers are available, or 1847 // indirectly if not. This avoids the need to align argument memory. Pass 1848 // user-defined vector types larger than 512 bits indirectly for simplicity. 1849 if (IsWin32StructABI) { 1850 if (TI.Width <= 512 && State.FreeSSERegs > 0) { 1851 --State.FreeSSERegs; 1852 return ABIArgInfo::getDirectInReg(); 1853 } 1854 return getIndirectResult(Ty, /*ByVal=*/false, State); 1855 } 1856 1857 // On Darwin, some vectors are passed in memory, we handle this by passing 1858 // it as an i8/i16/i32/i64. 1859 if (IsDarwinVectorABI) { 1860 if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) || 1861 (TI.Width == 64 && VT->getNumElements() == 1)) 1862 return ABIArgInfo::getDirect( 1863 llvm::IntegerType::get(getVMContext(), TI.Width)); 1864 } 1865 1866 if (IsX86_MMXType(CGT.ConvertType(Ty))) 1867 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64)); 1868 1869 return ABIArgInfo::getDirect(); 1870 } 1871 1872 1873 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1874 Ty = EnumTy->getDecl()->getIntegerType(); 1875 1876 bool InReg = shouldPrimitiveUseInReg(Ty, State); 1877 1878 if (isPromotableIntegerTypeForABI(Ty)) { 1879 if (InReg) 1880 return ABIArgInfo::getExtendInReg(Ty); 1881 return ABIArgInfo::getExtend(Ty); 1882 } 1883 1884 if (const auto * EIT = Ty->getAs<ExtIntType>()) { 1885 if (EIT->getNumBits() <= 64) { 1886 if (InReg) 1887 return ABIArgInfo::getDirectInReg(); 1888 return ABIArgInfo::getDirect(); 1889 } 1890 return getIndirectResult(Ty, /*ByVal=*/false, State); 1891 } 1892 1893 if (InReg) 1894 return ABIArgInfo::getDirectInReg(); 1895 return ABIArgInfo::getDirect(); 1896 } 1897 1898 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const { 1899 CCState State(FI); 1900 if (IsMCUABI) 1901 State.FreeRegs = 3; 1902 else if (State.CC == llvm::CallingConv::X86_FastCall) { 1903 State.FreeRegs = 2; 1904 State.FreeSSERegs = 3; 1905 } else if (State.CC == llvm::CallingConv::X86_VectorCall) { 1906 State.FreeRegs = 2; 1907 State.FreeSSERegs = 6; 1908 } else if (FI.getHasRegParm()) 1909 State.FreeRegs = FI.getRegParm(); 1910 else if (State.CC == llvm::CallingConv::X86_RegCall) { 1911 State.FreeRegs = 5; 1912 State.FreeSSERegs = 8; 1913 } else if (IsWin32StructABI) { 1914 // Since MSVC 2015, the first three SSE vectors have been passed in 1915 // registers. The rest are passed indirectly. 1916 State.FreeRegs = DefaultNumRegisterParameters; 1917 State.FreeSSERegs = 3; 1918 } else 1919 State.FreeRegs = DefaultNumRegisterParameters; 1920 1921 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 1922 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State); 1923 } else if (FI.getReturnInfo().isIndirect()) { 1924 // The C++ ABI is not aware of register usage, so we have to check if the 1925 // return value was sret and put it in a register ourselves if appropriate. 1926 if (State.FreeRegs) { 1927 --State.FreeRegs; // The sret parameter consumes a register. 1928 if (!IsMCUABI) 1929 FI.getReturnInfo().setInReg(true); 1930 } 1931 } 1932 1933 // The chain argument effectively gives us another free register. 1934 if (FI.isChainCall()) 1935 ++State.FreeRegs; 1936 1937 // For vectorcall, do a first pass over the arguments, assigning FP and vector 1938 // arguments to XMM registers as available. 1939 if (State.CC == llvm::CallingConv::X86_VectorCall) 1940 runVectorCallFirstPass(FI, State); 1941 1942 bool UsedInAlloca = false; 1943 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments(); 1944 for (int I = 0, E = Args.size(); I < E; ++I) { 1945 // Skip arguments that have already been assigned. 1946 if (State.IsPreassigned.test(I)) 1947 continue; 1948 1949 Args[I].info = classifyArgumentType(Args[I].type, State); 1950 UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca); 1951 } 1952 1953 // If we needed to use inalloca for any argument, do a second pass and rewrite 1954 // all the memory arguments to use inalloca. 1955 if (UsedInAlloca) 1956 rewriteWithInAlloca(FI); 1957 } 1958 1959 void 1960 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1961 CharUnits &StackOffset, ABIArgInfo &Info, 1962 QualType Type) const { 1963 // Arguments are always 4-byte-aligned. 1964 CharUnits WordSize = CharUnits::fromQuantity(4); 1965 assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct"); 1966 1967 // sret pointers and indirect things will require an extra pointer 1968 // indirection, unless they are byval. Most things are byval, and will not 1969 // require this indirection. 1970 bool IsIndirect = false; 1971 if (Info.isIndirect() && !Info.getIndirectByVal()) 1972 IsIndirect = true; 1973 Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect); 1974 llvm::Type *LLTy = CGT.ConvertTypeForMem(Type); 1975 if (IsIndirect) 1976 LLTy = LLTy->getPointerTo(0); 1977 FrameFields.push_back(LLTy); 1978 StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type); 1979 1980 // Insert padding bytes to respect alignment. 1981 CharUnits FieldEnd = StackOffset; 1982 StackOffset = FieldEnd.alignTo(WordSize); 1983 if (StackOffset != FieldEnd) { 1984 CharUnits NumBytes = StackOffset - FieldEnd; 1985 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext()); 1986 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity()); 1987 FrameFields.push_back(Ty); 1988 } 1989 } 1990 1991 static bool isArgInAlloca(const ABIArgInfo &Info) { 1992 // Leave ignored and inreg arguments alone. 1993 switch (Info.getKind()) { 1994 case ABIArgInfo::InAlloca: 1995 return true; 1996 case ABIArgInfo::Ignore: 1997 case ABIArgInfo::IndirectAliased: 1998 return false; 1999 case ABIArgInfo::Indirect: 2000 case ABIArgInfo::Direct: 2001 case ABIArgInfo::Extend: 2002 return !Info.getInReg(); 2003 case ABIArgInfo::Expand: 2004 case ABIArgInfo::CoerceAndExpand: 2005 // These are aggregate types which are never passed in registers when 2006 // inalloca is involved. 2007 return true; 2008 } 2009 llvm_unreachable("invalid enum"); 2010 } 2011 2012 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const { 2013 assert(IsWin32StructABI && "inalloca only supported on win32"); 2014 2015 // Build a packed struct type for all of the arguments in memory. 2016 SmallVector<llvm::Type *, 6> FrameFields; 2017 2018 // The stack alignment is always 4. 2019 CharUnits StackAlign = CharUnits::fromQuantity(4); 2020 2021 CharUnits StackOffset; 2022 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end(); 2023 2024 // Put 'this' into the struct before 'sret', if necessary. 2025 bool IsThisCall = 2026 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall; 2027 ABIArgInfo &Ret = FI.getReturnInfo(); 2028 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall && 2029 isArgInAlloca(I->info)) { 2030 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 2031 ++I; 2032 } 2033 2034 // Put the sret parameter into the inalloca struct if it's in memory. 2035 if (Ret.isIndirect() && !Ret.getInReg()) { 2036 addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType()); 2037 // On Windows, the hidden sret parameter is always returned in eax. 2038 Ret.setInAllocaSRet(IsWin32StructABI); 2039 } 2040 2041 // Skip the 'this' parameter in ecx. 2042 if (IsThisCall) 2043 ++I; 2044 2045 // Put arguments passed in memory into the struct. 2046 for (; I != E; ++I) { 2047 if (isArgInAlloca(I->info)) 2048 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 2049 } 2050 2051 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields, 2052 /*isPacked=*/true), 2053 StackAlign); 2054 } 2055 2056 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF, 2057 Address VAListAddr, QualType Ty) const { 2058 2059 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 2060 2061 // x86-32 changes the alignment of certain arguments on the stack. 2062 // 2063 // Just messing with TypeInfo like this works because we never pass 2064 // anything indirectly. 2065 TypeInfo.Align = CharUnits::fromQuantity( 2066 getTypeStackAlignInBytes(Ty, TypeInfo.Align.getQuantity())); 2067 2068 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 2069 TypeInfo, CharUnits::fromQuantity(4), 2070 /*AllowHigherAlign*/ true); 2071 } 2072 2073 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI( 2074 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 2075 assert(Triple.getArch() == llvm::Triple::x86); 2076 2077 switch (Opts.getStructReturnConvention()) { 2078 case CodeGenOptions::SRCK_Default: 2079 break; 2080 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return 2081 return false; 2082 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return 2083 return true; 2084 } 2085 2086 if (Triple.isOSDarwin() || Triple.isOSIAMCU()) 2087 return true; 2088 2089 switch (Triple.getOS()) { 2090 case llvm::Triple::DragonFly: 2091 case llvm::Triple::FreeBSD: 2092 case llvm::Triple::OpenBSD: 2093 case llvm::Triple::Win32: 2094 return true; 2095 default: 2096 return false; 2097 } 2098 } 2099 2100 void X86_32TargetCodeGenInfo::setTargetAttributes( 2101 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2102 if (GV->isDeclaration()) 2103 return; 2104 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2105 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2106 llvm::Function *Fn = cast<llvm::Function>(GV); 2107 Fn->addFnAttr("stackrealign"); 2108 } 2109 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2110 llvm::Function *Fn = cast<llvm::Function>(GV); 2111 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2112 } 2113 } 2114 } 2115 2116 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( 2117 CodeGen::CodeGenFunction &CGF, 2118 llvm::Value *Address) const { 2119 CodeGen::CGBuilderTy &Builder = CGF.Builder; 2120 2121 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 2122 2123 // 0-7 are the eight integer registers; the order is different 2124 // on Darwin (for EH), but the range is the same. 2125 // 8 is %eip. 2126 AssignToArrayRange(Builder, Address, Four8, 0, 8); 2127 2128 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) { 2129 // 12-16 are st(0..4). Not sure why we stop at 4. 2130 // These have size 16, which is sizeof(long double) on 2131 // platforms with 8-byte alignment for that type. 2132 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 2133 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); 2134 2135 } else { 2136 // 9 is %eflags, which doesn't get a size on Darwin for some 2137 // reason. 2138 Builder.CreateAlignedStore( 2139 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9), 2140 CharUnits::One()); 2141 2142 // 11-16 are st(0..5). Not sure why we stop at 5. 2143 // These have size 12, which is sizeof(long double) on 2144 // platforms with 4-byte alignment for that type. 2145 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); 2146 AssignToArrayRange(Builder, Address, Twelve8, 11, 16); 2147 } 2148 2149 return false; 2150 } 2151 2152 //===----------------------------------------------------------------------===// 2153 // X86-64 ABI Implementation 2154 //===----------------------------------------------------------------------===// 2155 2156 2157 namespace { 2158 /// The AVX ABI level for X86 targets. 2159 enum class X86AVXABILevel { 2160 None, 2161 AVX, 2162 AVX512 2163 }; 2164 2165 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel. 2166 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) { 2167 switch (AVXLevel) { 2168 case X86AVXABILevel::AVX512: 2169 return 512; 2170 case X86AVXABILevel::AVX: 2171 return 256; 2172 case X86AVXABILevel::None: 2173 return 128; 2174 } 2175 llvm_unreachable("Unknown AVXLevel"); 2176 } 2177 2178 /// X86_64ABIInfo - The X86_64 ABI information. 2179 class X86_64ABIInfo : public SwiftABIInfo { 2180 enum Class { 2181 Integer = 0, 2182 SSE, 2183 SSEUp, 2184 X87, 2185 X87Up, 2186 ComplexX87, 2187 NoClass, 2188 Memory 2189 }; 2190 2191 /// merge - Implement the X86_64 ABI merging algorithm. 2192 /// 2193 /// Merge an accumulating classification \arg Accum with a field 2194 /// classification \arg Field. 2195 /// 2196 /// \param Accum - The accumulating classification. This should 2197 /// always be either NoClass or the result of a previous merge 2198 /// call. In addition, this should never be Memory (the caller 2199 /// should just return Memory for the aggregate). 2200 static Class merge(Class Accum, Class Field); 2201 2202 /// postMerge - Implement the X86_64 ABI post merging algorithm. 2203 /// 2204 /// Post merger cleanup, reduces a malformed Hi and Lo pair to 2205 /// final MEMORY or SSE classes when necessary. 2206 /// 2207 /// \param AggregateSize - The size of the current aggregate in 2208 /// the classification process. 2209 /// 2210 /// \param Lo - The classification for the parts of the type 2211 /// residing in the low word of the containing object. 2212 /// 2213 /// \param Hi - The classification for the parts of the type 2214 /// residing in the higher words of the containing object. 2215 /// 2216 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; 2217 2218 /// classify - Determine the x86_64 register classes in which the 2219 /// given type T should be passed. 2220 /// 2221 /// \param Lo - The classification for the parts of the type 2222 /// residing in the low word of the containing object. 2223 /// 2224 /// \param Hi - The classification for the parts of the type 2225 /// residing in the high word of the containing object. 2226 /// 2227 /// \param OffsetBase - The bit offset of this type in the 2228 /// containing object. Some parameters are classified different 2229 /// depending on whether they straddle an eightbyte boundary. 2230 /// 2231 /// \param isNamedArg - Whether the argument in question is a "named" 2232 /// argument, as used in AMD64-ABI 3.5.7. 2233 /// 2234 /// If a word is unused its result will be NoClass; if a type should 2235 /// be passed in Memory then at least the classification of \arg Lo 2236 /// will be Memory. 2237 /// 2238 /// The \arg Lo class will be NoClass iff the argument is ignored. 2239 /// 2240 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will 2241 /// also be ComplexX87. 2242 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi, 2243 bool isNamedArg) const; 2244 2245 llvm::Type *GetByteVectorType(QualType Ty) const; 2246 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, 2247 unsigned IROffset, QualType SourceTy, 2248 unsigned SourceOffset) const; 2249 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, 2250 unsigned IROffset, QualType SourceTy, 2251 unsigned SourceOffset) const; 2252 2253 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2254 /// such that the argument will be returned in memory. 2255 ABIArgInfo getIndirectReturnResult(QualType Ty) const; 2256 2257 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2258 /// such that the argument will be passed in memory. 2259 /// 2260 /// \param freeIntRegs - The number of free integer registers remaining 2261 /// available. 2262 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const; 2263 2264 ABIArgInfo classifyReturnType(QualType RetTy) const; 2265 2266 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs, 2267 unsigned &neededInt, unsigned &neededSSE, 2268 bool isNamedArg) const; 2269 2270 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt, 2271 unsigned &NeededSSE) const; 2272 2273 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 2274 unsigned &NeededSSE) const; 2275 2276 bool IsIllegalVectorType(QualType Ty) const; 2277 2278 /// The 0.98 ABI revision clarified a lot of ambiguities, 2279 /// unfortunately in ways that were not always consistent with 2280 /// certain previous compilers. In particular, platforms which 2281 /// required strict binary compatibility with older versions of GCC 2282 /// may need to exempt themselves. 2283 bool honorsRevision0_98() const { 2284 return !getTarget().getTriple().isOSDarwin(); 2285 } 2286 2287 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to 2288 /// classify it as INTEGER (for compatibility with older clang compilers). 2289 bool classifyIntegerMMXAsSSE() const { 2290 // Clang <= 3.8 did not do this. 2291 if (getContext().getLangOpts().getClangABICompat() <= 2292 LangOptions::ClangABI::Ver3_8) 2293 return false; 2294 2295 const llvm::Triple &Triple = getTarget().getTriple(); 2296 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4) 2297 return false; 2298 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10) 2299 return false; 2300 return true; 2301 } 2302 2303 // GCC classifies vectors of __int128 as memory. 2304 bool passInt128VectorsInMem() const { 2305 // Clang <= 9.0 did not do this. 2306 if (getContext().getLangOpts().getClangABICompat() <= 2307 LangOptions::ClangABI::Ver9) 2308 return false; 2309 2310 const llvm::Triple &T = getTarget().getTriple(); 2311 return T.isOSLinux() || T.isOSNetBSD(); 2312 } 2313 2314 X86AVXABILevel AVXLevel; 2315 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on 2316 // 64-bit hardware. 2317 bool Has64BitPointers; 2318 2319 public: 2320 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) : 2321 SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2322 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) { 2323 } 2324 2325 bool isPassedUsingAVXType(QualType type) const { 2326 unsigned neededInt, neededSSE; 2327 // The freeIntRegs argument doesn't matter here. 2328 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE, 2329 /*isNamedArg*/true); 2330 if (info.isDirect()) { 2331 llvm::Type *ty = info.getCoerceToType(); 2332 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty)) 2333 return vectorTy->getPrimitiveSizeInBits().getFixedSize() > 128; 2334 } 2335 return false; 2336 } 2337 2338 void computeInfo(CGFunctionInfo &FI) const override; 2339 2340 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2341 QualType Ty) const override; 2342 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 2343 QualType Ty) const override; 2344 2345 bool has64BitPointers() const { 2346 return Has64BitPointers; 2347 } 2348 2349 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 2350 bool asReturnValue) const override { 2351 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2352 } 2353 bool isSwiftErrorInRegister() const override { 2354 return true; 2355 } 2356 }; 2357 2358 /// WinX86_64ABIInfo - The Windows X86_64 ABI information. 2359 class WinX86_64ABIInfo : public SwiftABIInfo { 2360 public: 2361 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2362 : SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2363 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {} 2364 2365 void computeInfo(CGFunctionInfo &FI) const override; 2366 2367 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2368 QualType Ty) const override; 2369 2370 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 2371 // FIXME: Assumes vectorcall is in use. 2372 return isX86VectorTypeForVectorCall(getContext(), Ty); 2373 } 2374 2375 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 2376 uint64_t NumMembers) const override { 2377 // FIXME: Assumes vectorcall is in use. 2378 return isX86VectorCallAggregateSmallEnough(NumMembers); 2379 } 2380 2381 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars, 2382 bool asReturnValue) const override { 2383 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2384 } 2385 2386 bool isSwiftErrorInRegister() const override { 2387 return true; 2388 } 2389 2390 private: 2391 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType, 2392 bool IsVectorCall, bool IsRegCall) const; 2393 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs, 2394 const ABIArgInfo ¤t) const; 2395 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs, 2396 bool IsVectorCall, bool IsRegCall) const; 2397 2398 X86AVXABILevel AVXLevel; 2399 2400 bool IsMingw64; 2401 }; 2402 2403 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2404 public: 2405 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2406 : TargetCodeGenInfo(std::make_unique<X86_64ABIInfo>(CGT, AVXLevel)) {} 2407 2408 const X86_64ABIInfo &getABIInfo() const { 2409 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 2410 } 2411 2412 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks 2413 /// autoreleaseRV/retainRV and autoreleaseRV/unsafeClaimRV optimizations. 2414 bool markARCOptimizedReturnCallsAsNoTail() const override { return true; } 2415 2416 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2417 return 7; 2418 } 2419 2420 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2421 llvm::Value *Address) const override { 2422 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2423 2424 // 0-15 are the 16 integer registers. 2425 // 16 is %rip. 2426 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2427 return false; 2428 } 2429 2430 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 2431 StringRef Constraint, 2432 llvm::Type* Ty) const override { 2433 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 2434 } 2435 2436 bool isNoProtoCallVariadic(const CallArgList &args, 2437 const FunctionNoProtoType *fnType) const override { 2438 // The default CC on x86-64 sets %al to the number of SSA 2439 // registers used, and GCC sets this when calling an unprototyped 2440 // function, so we override the default behavior. However, don't do 2441 // that when AVX types are involved: the ABI explicitly states it is 2442 // undefined, and it doesn't work in practice because of how the ABI 2443 // defines varargs anyway. 2444 if (fnType->getCallConv() == CC_C) { 2445 bool HasAVXType = false; 2446 for (CallArgList::const_iterator 2447 it = args.begin(), ie = args.end(); it != ie; ++it) { 2448 if (getABIInfo().isPassedUsingAVXType(it->Ty)) { 2449 HasAVXType = true; 2450 break; 2451 } 2452 } 2453 2454 if (!HasAVXType) 2455 return true; 2456 } 2457 2458 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); 2459 } 2460 2461 llvm::Constant * 2462 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 2463 unsigned Sig = (0xeb << 0) | // jmp rel8 2464 (0x06 << 8) | // .+0x08 2465 ('v' << 16) | 2466 ('2' << 24); 2467 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 2468 } 2469 2470 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2471 CodeGen::CodeGenModule &CGM) const override { 2472 if (GV->isDeclaration()) 2473 return; 2474 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2475 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2476 llvm::Function *Fn = cast<llvm::Function>(GV); 2477 Fn->addFnAttr("stackrealign"); 2478 } 2479 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2480 llvm::Function *Fn = cast<llvm::Function>(GV); 2481 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2482 } 2483 } 2484 } 2485 2486 void checkFunctionCallABI(CodeGenModule &CGM, SourceLocation CallLoc, 2487 const FunctionDecl *Caller, 2488 const FunctionDecl *Callee, 2489 const CallArgList &Args) const override; 2490 }; 2491 2492 static void initFeatureMaps(const ASTContext &Ctx, 2493 llvm::StringMap<bool> &CallerMap, 2494 const FunctionDecl *Caller, 2495 llvm::StringMap<bool> &CalleeMap, 2496 const FunctionDecl *Callee) { 2497 if (CalleeMap.empty() && CallerMap.empty()) { 2498 // The caller is potentially nullptr in the case where the call isn't in a 2499 // function. In this case, the getFunctionFeatureMap ensures we just get 2500 // the TU level setting (since it cannot be modified by 'target'.. 2501 Ctx.getFunctionFeatureMap(CallerMap, Caller); 2502 Ctx.getFunctionFeatureMap(CalleeMap, Callee); 2503 } 2504 } 2505 2506 static bool checkAVXParamFeature(DiagnosticsEngine &Diag, 2507 SourceLocation CallLoc, 2508 const llvm::StringMap<bool> &CallerMap, 2509 const llvm::StringMap<bool> &CalleeMap, 2510 QualType Ty, StringRef Feature, 2511 bool IsArgument) { 2512 bool CallerHasFeat = CallerMap.lookup(Feature); 2513 bool CalleeHasFeat = CalleeMap.lookup(Feature); 2514 if (!CallerHasFeat && !CalleeHasFeat) 2515 return Diag.Report(CallLoc, diag::warn_avx_calling_convention) 2516 << IsArgument << Ty << Feature; 2517 2518 // Mixing calling conventions here is very clearly an error. 2519 if (!CallerHasFeat || !CalleeHasFeat) 2520 return Diag.Report(CallLoc, diag::err_avx_calling_convention) 2521 << IsArgument << Ty << Feature; 2522 2523 // Else, both caller and callee have the required feature, so there is no need 2524 // to diagnose. 2525 return false; 2526 } 2527 2528 static bool checkAVXParam(DiagnosticsEngine &Diag, ASTContext &Ctx, 2529 SourceLocation CallLoc, 2530 const llvm::StringMap<bool> &CallerMap, 2531 const llvm::StringMap<bool> &CalleeMap, QualType Ty, 2532 bool IsArgument) { 2533 uint64_t Size = Ctx.getTypeSize(Ty); 2534 if (Size > 256) 2535 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, 2536 "avx512f", IsArgument); 2537 2538 if (Size > 128) 2539 return checkAVXParamFeature(Diag, CallLoc, CallerMap, CalleeMap, Ty, "avx", 2540 IsArgument); 2541 2542 return false; 2543 } 2544 2545 void X86_64TargetCodeGenInfo::checkFunctionCallABI( 2546 CodeGenModule &CGM, SourceLocation CallLoc, const FunctionDecl *Caller, 2547 const FunctionDecl *Callee, const CallArgList &Args) const { 2548 llvm::StringMap<bool> CallerMap; 2549 llvm::StringMap<bool> CalleeMap; 2550 unsigned ArgIndex = 0; 2551 2552 // We need to loop through the actual call arguments rather than the the 2553 // function's parameters, in case this variadic. 2554 for (const CallArg &Arg : Args) { 2555 // The "avx" feature changes how vectors >128 in size are passed. "avx512f" 2556 // additionally changes how vectors >256 in size are passed. Like GCC, we 2557 // warn when a function is called with an argument where this will change. 2558 // Unlike GCC, we also error when it is an obvious ABI mismatch, that is, 2559 // the caller and callee features are mismatched. 2560 // Unfortunately, we cannot do this diagnostic in SEMA, since the callee can 2561 // change its ABI with attribute-target after this call. 2562 if (Arg.getType()->isVectorType() && 2563 CGM.getContext().getTypeSize(Arg.getType()) > 128) { 2564 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee); 2565 QualType Ty = Arg.getType(); 2566 // The CallArg seems to have desugared the type already, so for clearer 2567 // diagnostics, replace it with the type in the FunctionDecl if possible. 2568 if (ArgIndex < Callee->getNumParams()) 2569 Ty = Callee->getParamDecl(ArgIndex)->getType(); 2570 2571 if (checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap, 2572 CalleeMap, Ty, /*IsArgument*/ true)) 2573 return; 2574 } 2575 ++ArgIndex; 2576 } 2577 2578 // Check return always, as we don't have a good way of knowing in codegen 2579 // whether this value is used, tail-called, etc. 2580 if (Callee->getReturnType()->isVectorType() && 2581 CGM.getContext().getTypeSize(Callee->getReturnType()) > 128) { 2582 initFeatureMaps(CGM.getContext(), CallerMap, Caller, CalleeMap, Callee); 2583 checkAVXParam(CGM.getDiags(), CGM.getContext(), CallLoc, CallerMap, 2584 CalleeMap, Callee->getReturnType(), 2585 /*IsArgument*/ false); 2586 } 2587 } 2588 2589 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) { 2590 // If the argument does not end in .lib, automatically add the suffix. 2591 // If the argument contains a space, enclose it in quotes. 2592 // This matches the behavior of MSVC. 2593 bool Quote = (Lib.find(" ") != StringRef::npos); 2594 std::string ArgStr = Quote ? "\"" : ""; 2595 ArgStr += Lib; 2596 if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a")) 2597 ArgStr += ".lib"; 2598 ArgStr += Quote ? "\"" : ""; 2599 return ArgStr; 2600 } 2601 2602 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo { 2603 public: 2604 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2605 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI, 2606 unsigned NumRegisterParameters) 2607 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI, 2608 Win32StructABI, NumRegisterParameters, false) {} 2609 2610 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2611 CodeGen::CodeGenModule &CGM) const override; 2612 2613 void getDependentLibraryOption(llvm::StringRef Lib, 2614 llvm::SmallString<24> &Opt) const override { 2615 Opt = "/DEFAULTLIB:"; 2616 Opt += qualifyWindowsLibrary(Lib); 2617 } 2618 2619 void getDetectMismatchOption(llvm::StringRef Name, 2620 llvm::StringRef Value, 2621 llvm::SmallString<32> &Opt) const override { 2622 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2623 } 2624 }; 2625 2626 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2627 CodeGen::CodeGenModule &CGM) { 2628 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) { 2629 2630 if (CGM.getCodeGenOpts().StackProbeSize != 4096) 2631 Fn->addFnAttr("stack-probe-size", 2632 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize)); 2633 if (CGM.getCodeGenOpts().NoStackArgProbe) 2634 Fn->addFnAttr("no-stack-arg-probe"); 2635 } 2636 } 2637 2638 void WinX86_32TargetCodeGenInfo::setTargetAttributes( 2639 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2640 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2641 if (GV->isDeclaration()) 2642 return; 2643 addStackProbeTargetAttributes(D, GV, CGM); 2644 } 2645 2646 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2647 public: 2648 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2649 X86AVXABILevel AVXLevel) 2650 : TargetCodeGenInfo(std::make_unique<WinX86_64ABIInfo>(CGT, AVXLevel)) {} 2651 2652 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2653 CodeGen::CodeGenModule &CGM) const override; 2654 2655 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2656 return 7; 2657 } 2658 2659 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2660 llvm::Value *Address) const override { 2661 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2662 2663 // 0-15 are the 16 integer registers. 2664 // 16 is %rip. 2665 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2666 return false; 2667 } 2668 2669 void getDependentLibraryOption(llvm::StringRef Lib, 2670 llvm::SmallString<24> &Opt) const override { 2671 Opt = "/DEFAULTLIB:"; 2672 Opt += qualifyWindowsLibrary(Lib); 2673 } 2674 2675 void getDetectMismatchOption(llvm::StringRef Name, 2676 llvm::StringRef Value, 2677 llvm::SmallString<32> &Opt) const override { 2678 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2679 } 2680 }; 2681 2682 void WinX86_64TargetCodeGenInfo::setTargetAttributes( 2683 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2684 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2685 if (GV->isDeclaration()) 2686 return; 2687 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2688 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2689 llvm::Function *Fn = cast<llvm::Function>(GV); 2690 Fn->addFnAttr("stackrealign"); 2691 } 2692 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2693 llvm::Function *Fn = cast<llvm::Function>(GV); 2694 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2695 } 2696 } 2697 2698 addStackProbeTargetAttributes(D, GV, CGM); 2699 } 2700 } 2701 2702 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, 2703 Class &Hi) const { 2704 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: 2705 // 2706 // (a) If one of the classes is Memory, the whole argument is passed in 2707 // memory. 2708 // 2709 // (b) If X87UP is not preceded by X87, the whole argument is passed in 2710 // memory. 2711 // 2712 // (c) If the size of the aggregate exceeds two eightbytes and the first 2713 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole 2714 // argument is passed in memory. NOTE: This is necessary to keep the 2715 // ABI working for processors that don't support the __m256 type. 2716 // 2717 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. 2718 // 2719 // Some of these are enforced by the merging logic. Others can arise 2720 // only with unions; for example: 2721 // union { _Complex double; unsigned; } 2722 // 2723 // Note that clauses (b) and (c) were added in 0.98. 2724 // 2725 if (Hi == Memory) 2726 Lo = Memory; 2727 if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) 2728 Lo = Memory; 2729 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) 2730 Lo = Memory; 2731 if (Hi == SSEUp && Lo != SSE) 2732 Hi = SSE; 2733 } 2734 2735 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { 2736 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is 2737 // classified recursively so that always two fields are 2738 // considered. The resulting class is calculated according to 2739 // the classes of the fields in the eightbyte: 2740 // 2741 // (a) If both classes are equal, this is the resulting class. 2742 // 2743 // (b) If one of the classes is NO_CLASS, the resulting class is 2744 // the other class. 2745 // 2746 // (c) If one of the classes is MEMORY, the result is the MEMORY 2747 // class. 2748 // 2749 // (d) If one of the classes is INTEGER, the result is the 2750 // INTEGER. 2751 // 2752 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, 2753 // MEMORY is used as class. 2754 // 2755 // (f) Otherwise class SSE is used. 2756 2757 // Accum should never be memory (we should have returned) or 2758 // ComplexX87 (because this cannot be passed in a structure). 2759 assert((Accum != Memory && Accum != ComplexX87) && 2760 "Invalid accumulated classification during merge."); 2761 if (Accum == Field || Field == NoClass) 2762 return Accum; 2763 if (Field == Memory) 2764 return Memory; 2765 if (Accum == NoClass) 2766 return Field; 2767 if (Accum == Integer || Field == Integer) 2768 return Integer; 2769 if (Field == X87 || Field == X87Up || Field == ComplexX87 || 2770 Accum == X87 || Accum == X87Up) 2771 return Memory; 2772 return SSE; 2773 } 2774 2775 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, 2776 Class &Lo, Class &Hi, bool isNamedArg) const { 2777 // FIXME: This code can be simplified by introducing a simple value class for 2778 // Class pairs with appropriate constructor methods for the various 2779 // situations. 2780 2781 // FIXME: Some of the split computations are wrong; unaligned vectors 2782 // shouldn't be passed in registers for example, so there is no chance they 2783 // can straddle an eightbyte. Verify & simplify. 2784 2785 Lo = Hi = NoClass; 2786 2787 Class &Current = OffsetBase < 64 ? Lo : Hi; 2788 Current = Memory; 2789 2790 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 2791 BuiltinType::Kind k = BT->getKind(); 2792 2793 if (k == BuiltinType::Void) { 2794 Current = NoClass; 2795 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { 2796 Lo = Integer; 2797 Hi = Integer; 2798 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { 2799 Current = Integer; 2800 } else if (k == BuiltinType::Float || k == BuiltinType::Double) { 2801 Current = SSE; 2802 } else if (k == BuiltinType::LongDouble) { 2803 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2804 if (LDF == &llvm::APFloat::IEEEquad()) { 2805 Lo = SSE; 2806 Hi = SSEUp; 2807 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) { 2808 Lo = X87; 2809 Hi = X87Up; 2810 } else if (LDF == &llvm::APFloat::IEEEdouble()) { 2811 Current = SSE; 2812 } else 2813 llvm_unreachable("unexpected long double representation!"); 2814 } 2815 // FIXME: _Decimal32 and _Decimal64 are SSE. 2816 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). 2817 return; 2818 } 2819 2820 if (const EnumType *ET = Ty->getAs<EnumType>()) { 2821 // Classify the underlying integer type. 2822 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg); 2823 return; 2824 } 2825 2826 if (Ty->hasPointerRepresentation()) { 2827 Current = Integer; 2828 return; 2829 } 2830 2831 if (Ty->isMemberPointerType()) { 2832 if (Ty->isMemberFunctionPointerType()) { 2833 if (Has64BitPointers) { 2834 // If Has64BitPointers, this is an {i64, i64}, so classify both 2835 // Lo and Hi now. 2836 Lo = Hi = Integer; 2837 } else { 2838 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that 2839 // straddles an eightbyte boundary, Hi should be classified as well. 2840 uint64_t EB_FuncPtr = (OffsetBase) / 64; 2841 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64; 2842 if (EB_FuncPtr != EB_ThisAdj) { 2843 Lo = Hi = Integer; 2844 } else { 2845 Current = Integer; 2846 } 2847 } 2848 } else { 2849 Current = Integer; 2850 } 2851 return; 2852 } 2853 2854 if (const VectorType *VT = Ty->getAs<VectorType>()) { 2855 uint64_t Size = getContext().getTypeSize(VT); 2856 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) { 2857 // gcc passes the following as integer: 2858 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float> 2859 // 2 bytes - <2 x char>, <1 x short> 2860 // 1 byte - <1 x char> 2861 Current = Integer; 2862 2863 // If this type crosses an eightbyte boundary, it should be 2864 // split. 2865 uint64_t EB_Lo = (OffsetBase) / 64; 2866 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64; 2867 if (EB_Lo != EB_Hi) 2868 Hi = Lo; 2869 } else if (Size == 64) { 2870 QualType ElementType = VT->getElementType(); 2871 2872 // gcc passes <1 x double> in memory. :( 2873 if (ElementType->isSpecificBuiltinType(BuiltinType::Double)) 2874 return; 2875 2876 // gcc passes <1 x long long> as SSE but clang used to unconditionally 2877 // pass them as integer. For platforms where clang is the de facto 2878 // platform compiler, we must continue to use integer. 2879 if (!classifyIntegerMMXAsSSE() && 2880 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) || 2881 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) || 2882 ElementType->isSpecificBuiltinType(BuiltinType::Long) || 2883 ElementType->isSpecificBuiltinType(BuiltinType::ULong))) 2884 Current = Integer; 2885 else 2886 Current = SSE; 2887 2888 // If this type crosses an eightbyte boundary, it should be 2889 // split. 2890 if (OffsetBase && OffsetBase != 64) 2891 Hi = Lo; 2892 } else if (Size == 128 || 2893 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) { 2894 QualType ElementType = VT->getElementType(); 2895 2896 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :( 2897 if (passInt128VectorsInMem() && Size != 128 && 2898 (ElementType->isSpecificBuiltinType(BuiltinType::Int128) || 2899 ElementType->isSpecificBuiltinType(BuiltinType::UInt128))) 2900 return; 2901 2902 // Arguments of 256-bits are split into four eightbyte chunks. The 2903 // least significant one belongs to class SSE and all the others to class 2904 // SSEUP. The original Lo and Hi design considers that types can't be 2905 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. 2906 // This design isn't correct for 256-bits, but since there're no cases 2907 // where the upper parts would need to be inspected, avoid adding 2908 // complexity and just consider Hi to match the 64-256 part. 2909 // 2910 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in 2911 // registers if they are "named", i.e. not part of the "..." of a 2912 // variadic function. 2913 // 2914 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are 2915 // split into eight eightbyte chunks, one SSE and seven SSEUP. 2916 Lo = SSE; 2917 Hi = SSEUp; 2918 } 2919 return; 2920 } 2921 2922 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 2923 QualType ET = getContext().getCanonicalType(CT->getElementType()); 2924 2925 uint64_t Size = getContext().getTypeSize(Ty); 2926 if (ET->isIntegralOrEnumerationType()) { 2927 if (Size <= 64) 2928 Current = Integer; 2929 else if (Size <= 128) 2930 Lo = Hi = Integer; 2931 } else if (ET == getContext().FloatTy) { 2932 Current = SSE; 2933 } else if (ET == getContext().DoubleTy) { 2934 Lo = Hi = SSE; 2935 } else if (ET == getContext().LongDoubleTy) { 2936 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2937 if (LDF == &llvm::APFloat::IEEEquad()) 2938 Current = Memory; 2939 else if (LDF == &llvm::APFloat::x87DoubleExtended()) 2940 Current = ComplexX87; 2941 else if (LDF == &llvm::APFloat::IEEEdouble()) 2942 Lo = Hi = SSE; 2943 else 2944 llvm_unreachable("unexpected long double representation!"); 2945 } 2946 2947 // If this complex type crosses an eightbyte boundary then it 2948 // should be split. 2949 uint64_t EB_Real = (OffsetBase) / 64; 2950 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; 2951 if (Hi == NoClass && EB_Real != EB_Imag) 2952 Hi = Lo; 2953 2954 return; 2955 } 2956 2957 if (const auto *EITy = Ty->getAs<ExtIntType>()) { 2958 if (EITy->getNumBits() <= 64) 2959 Current = Integer; 2960 else if (EITy->getNumBits() <= 128) 2961 Lo = Hi = Integer; 2962 // Larger values need to get passed in memory. 2963 return; 2964 } 2965 2966 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 2967 // Arrays are treated like structures. 2968 2969 uint64_t Size = getContext().getTypeSize(Ty); 2970 2971 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 2972 // than eight eightbytes, ..., it has class MEMORY. 2973 if (Size > 512) 2974 return; 2975 2976 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned 2977 // fields, it has class MEMORY. 2978 // 2979 // Only need to check alignment of array base. 2980 if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) 2981 return; 2982 2983 // Otherwise implement simplified merge. We could be smarter about 2984 // this, but it isn't worth it and would be harder to verify. 2985 Current = NoClass; 2986 uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); 2987 uint64_t ArraySize = AT->getSize().getZExtValue(); 2988 2989 // The only case a 256-bit wide vector could be used is when the array 2990 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 2991 // to work for sizes wider than 128, early check and fallback to memory. 2992 // 2993 if (Size > 128 && 2994 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel))) 2995 return; 2996 2997 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { 2998 Class FieldLo, FieldHi; 2999 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg); 3000 Lo = merge(Lo, FieldLo); 3001 Hi = merge(Hi, FieldHi); 3002 if (Lo == Memory || Hi == Memory) 3003 break; 3004 } 3005 3006 postMerge(Size, Lo, Hi); 3007 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); 3008 return; 3009 } 3010 3011 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3012 uint64_t Size = getContext().getTypeSize(Ty); 3013 3014 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 3015 // than eight eightbytes, ..., it has class MEMORY. 3016 if (Size > 512) 3017 return; 3018 3019 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial 3020 // copy constructor or a non-trivial destructor, it is passed by invisible 3021 // reference. 3022 if (getRecordArgABI(RT, getCXXABI())) 3023 return; 3024 3025 const RecordDecl *RD = RT->getDecl(); 3026 3027 // Assume variable sized types are passed in memory. 3028 if (RD->hasFlexibleArrayMember()) 3029 return; 3030 3031 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 3032 3033 // Reset Lo class, this will be recomputed. 3034 Current = NoClass; 3035 3036 // If this is a C++ record, classify the bases first. 3037 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3038 for (const auto &I : CXXRD->bases()) { 3039 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3040 "Unexpected base class!"); 3041 const auto *Base = 3042 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3043 3044 // Classify this field. 3045 // 3046 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a 3047 // single eightbyte, each is classified separately. Each eightbyte gets 3048 // initialized to class NO_CLASS. 3049 Class FieldLo, FieldHi; 3050 uint64_t Offset = 3051 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base)); 3052 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg); 3053 Lo = merge(Lo, FieldLo); 3054 Hi = merge(Hi, FieldHi); 3055 if (Lo == Memory || Hi == Memory) { 3056 postMerge(Size, Lo, Hi); 3057 return; 3058 } 3059 } 3060 } 3061 3062 // Classify the fields one at a time, merging the results. 3063 unsigned idx = 0; 3064 bool UseClang11Compat = getContext().getLangOpts().getClangABICompat() <= 3065 LangOptions::ClangABI::Ver11 || 3066 getContext().getTargetInfo().getTriple().isPS4(); 3067 bool IsUnion = RT->isUnionType() && !UseClang11Compat; 3068 3069 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3070 i != e; ++i, ++idx) { 3071 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 3072 bool BitField = i->isBitField(); 3073 3074 // Ignore padding bit-fields. 3075 if (BitField && i->isUnnamedBitfield()) 3076 continue; 3077 3078 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than 3079 // eight eightbytes, or it contains unaligned fields, it has class MEMORY. 3080 // 3081 // The only case a 256-bit or a 512-bit wide vector could be used is when 3082 // the struct contains a single 256-bit or 512-bit element. Early check 3083 // and fallback to memory. 3084 // 3085 // FIXME: Extended the Lo and Hi logic properly to work for size wider 3086 // than 128. 3087 if (Size > 128 && 3088 ((!IsUnion && Size != getContext().getTypeSize(i->getType())) || 3089 Size > getNativeVectorSizeForAVXABI(AVXLevel))) { 3090 Lo = Memory; 3091 postMerge(Size, Lo, Hi); 3092 return; 3093 } 3094 // Note, skip this test for bit-fields, see below. 3095 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { 3096 Lo = Memory; 3097 postMerge(Size, Lo, Hi); 3098 return; 3099 } 3100 3101 // Classify this field. 3102 // 3103 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate 3104 // exceeds a single eightbyte, each is classified 3105 // separately. Each eightbyte gets initialized to class 3106 // NO_CLASS. 3107 Class FieldLo, FieldHi; 3108 3109 // Bit-fields require special handling, they do not force the 3110 // structure to be passed in memory even if unaligned, and 3111 // therefore they can straddle an eightbyte. 3112 if (BitField) { 3113 assert(!i->isUnnamedBitfield()); 3114 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 3115 uint64_t Size = i->getBitWidthValue(getContext()); 3116 3117 uint64_t EB_Lo = Offset / 64; 3118 uint64_t EB_Hi = (Offset + Size - 1) / 64; 3119 3120 if (EB_Lo) { 3121 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); 3122 FieldLo = NoClass; 3123 FieldHi = Integer; 3124 } else { 3125 FieldLo = Integer; 3126 FieldHi = EB_Hi ? Integer : NoClass; 3127 } 3128 } else 3129 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); 3130 Lo = merge(Lo, FieldLo); 3131 Hi = merge(Hi, FieldHi); 3132 if (Lo == Memory || Hi == Memory) 3133 break; 3134 } 3135 3136 postMerge(Size, Lo, Hi); 3137 } 3138 } 3139 3140 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { 3141 // If this is a scalar LLVM value then assume LLVM will pass it in the right 3142 // place naturally. 3143 if (!isAggregateTypeForABI(Ty)) { 3144 // Treat an enum type as its underlying type. 3145 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3146 Ty = EnumTy->getDecl()->getIntegerType(); 3147 3148 if (Ty->isExtIntType()) 3149 return getNaturalAlignIndirect(Ty); 3150 3151 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 3152 : ABIArgInfo::getDirect()); 3153 } 3154 3155 return getNaturalAlignIndirect(Ty); 3156 } 3157 3158 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { 3159 if (const VectorType *VecTy = Ty->getAs<VectorType>()) { 3160 uint64_t Size = getContext().getTypeSize(VecTy); 3161 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel); 3162 if (Size <= 64 || Size > LargestVector) 3163 return true; 3164 QualType EltTy = VecTy->getElementType(); 3165 if (passInt128VectorsInMem() && 3166 (EltTy->isSpecificBuiltinType(BuiltinType::Int128) || 3167 EltTy->isSpecificBuiltinType(BuiltinType::UInt128))) 3168 return true; 3169 } 3170 3171 return false; 3172 } 3173 3174 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty, 3175 unsigned freeIntRegs) const { 3176 // If this is a scalar LLVM value then assume LLVM will pass it in the right 3177 // place naturally. 3178 // 3179 // This assumption is optimistic, as there could be free registers available 3180 // when we need to pass this argument in memory, and LLVM could try to pass 3181 // the argument in the free register. This does not seem to happen currently, 3182 // but this code would be much safer if we could mark the argument with 3183 // 'onstack'. See PR12193. 3184 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty) && 3185 !Ty->isExtIntType()) { 3186 // Treat an enum type as its underlying type. 3187 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3188 Ty = EnumTy->getDecl()->getIntegerType(); 3189 3190 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 3191 : ABIArgInfo::getDirect()); 3192 } 3193 3194 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 3195 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 3196 3197 // Compute the byval alignment. We specify the alignment of the byval in all 3198 // cases so that the mid-level optimizer knows the alignment of the byval. 3199 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); 3200 3201 // Attempt to avoid passing indirect results using byval when possible. This 3202 // is important for good codegen. 3203 // 3204 // We do this by coercing the value into a scalar type which the backend can 3205 // handle naturally (i.e., without using byval). 3206 // 3207 // For simplicity, we currently only do this when we have exhausted all of the 3208 // free integer registers. Doing this when there are free integer registers 3209 // would require more care, as we would have to ensure that the coerced value 3210 // did not claim the unused register. That would require either reording the 3211 // arguments to the function (so that any subsequent inreg values came first), 3212 // or only doing this optimization when there were no following arguments that 3213 // might be inreg. 3214 // 3215 // We currently expect it to be rare (particularly in well written code) for 3216 // arguments to be passed on the stack when there are still free integer 3217 // registers available (this would typically imply large structs being passed 3218 // by value), so this seems like a fair tradeoff for now. 3219 // 3220 // We can revisit this if the backend grows support for 'onstack' parameter 3221 // attributes. See PR12193. 3222 if (freeIntRegs == 0) { 3223 uint64_t Size = getContext().getTypeSize(Ty); 3224 3225 // If this type fits in an eightbyte, coerce it into the matching integral 3226 // type, which will end up on the stack (with alignment 8). 3227 if (Align == 8 && Size <= 64) 3228 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 3229 Size)); 3230 } 3231 3232 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align)); 3233 } 3234 3235 /// The ABI specifies that a value should be passed in a full vector XMM/YMM 3236 /// register. Pick an LLVM IR type that will be passed as a vector register. 3237 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { 3238 // Wrapper structs/arrays that only contain vectors are passed just like 3239 // vectors; strip them off if present. 3240 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext())) 3241 Ty = QualType(InnerTy, 0); 3242 3243 llvm::Type *IRType = CGT.ConvertType(Ty); 3244 if (isa<llvm::VectorType>(IRType)) { 3245 // Don't pass vXi128 vectors in their native type, the backend can't 3246 // legalize them. 3247 if (passInt128VectorsInMem() && 3248 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy(128)) { 3249 // Use a vXi64 vector. 3250 uint64_t Size = getContext().getTypeSize(Ty); 3251 return llvm::FixedVectorType::get(llvm::Type::getInt64Ty(getVMContext()), 3252 Size / 64); 3253 } 3254 3255 return IRType; 3256 } 3257 3258 if (IRType->getTypeID() == llvm::Type::FP128TyID) 3259 return IRType; 3260 3261 // We couldn't find the preferred IR vector type for 'Ty'. 3262 uint64_t Size = getContext().getTypeSize(Ty); 3263 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!"); 3264 3265 3266 // Return a LLVM IR vector type based on the size of 'Ty'. 3267 return llvm::FixedVectorType::get(llvm::Type::getDoubleTy(getVMContext()), 3268 Size / 64); 3269 } 3270 3271 /// BitsContainNoUserData - Return true if the specified [start,end) bit range 3272 /// is known to either be off the end of the specified type or being in 3273 /// alignment padding. The user type specified is known to be at most 128 bits 3274 /// in size, and have passed through X86_64ABIInfo::classify with a successful 3275 /// classification that put one of the two halves in the INTEGER class. 3276 /// 3277 /// It is conservatively correct to return false. 3278 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, 3279 unsigned EndBit, ASTContext &Context) { 3280 // If the bytes being queried are off the end of the type, there is no user 3281 // data hiding here. This handles analysis of builtins, vectors and other 3282 // types that don't contain interesting padding. 3283 unsigned TySize = (unsigned)Context.getTypeSize(Ty); 3284 if (TySize <= StartBit) 3285 return true; 3286 3287 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 3288 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); 3289 unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); 3290 3291 // Check each element to see if the element overlaps with the queried range. 3292 for (unsigned i = 0; i != NumElts; ++i) { 3293 // If the element is after the span we care about, then we're done.. 3294 unsigned EltOffset = i*EltSize; 3295 if (EltOffset >= EndBit) break; 3296 3297 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; 3298 if (!BitsContainNoUserData(AT->getElementType(), EltStart, 3299 EndBit-EltOffset, Context)) 3300 return false; 3301 } 3302 // If it overlaps no elements, then it is safe to process as padding. 3303 return true; 3304 } 3305 3306 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3307 const RecordDecl *RD = RT->getDecl(); 3308 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 3309 3310 // If this is a C++ record, check the bases first. 3311 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3312 for (const auto &I : CXXRD->bases()) { 3313 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3314 "Unexpected base class!"); 3315 const auto *Base = 3316 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 3317 3318 // If the base is after the span we care about, ignore it. 3319 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base)); 3320 if (BaseOffset >= EndBit) continue; 3321 3322 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; 3323 if (!BitsContainNoUserData(I.getType(), BaseStart, 3324 EndBit-BaseOffset, Context)) 3325 return false; 3326 } 3327 } 3328 3329 // Verify that no field has data that overlaps the region of interest. Yes 3330 // this could be sped up a lot by being smarter about queried fields, 3331 // however we're only looking at structs up to 16 bytes, so we don't care 3332 // much. 3333 unsigned idx = 0; 3334 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3335 i != e; ++i, ++idx) { 3336 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); 3337 3338 // If we found a field after the region we care about, then we're done. 3339 if (FieldOffset >= EndBit) break; 3340 3341 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; 3342 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, 3343 Context)) 3344 return false; 3345 } 3346 3347 // If nothing in this record overlapped the area of interest, then we're 3348 // clean. 3349 return true; 3350 } 3351 3352 return false; 3353 } 3354 3355 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a 3356 /// float member at the specified offset. For example, {int,{float}} has a 3357 /// float at offset 4. It is conservatively correct for this routine to return 3358 /// false. 3359 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset, 3360 const llvm::DataLayout &TD) { 3361 // Base case if we find a float. 3362 if (IROffset == 0 && IRType->isFloatTy()) 3363 return true; 3364 3365 // If this is a struct, recurse into the field at the specified offset. 3366 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3367 const llvm::StructLayout *SL = TD.getStructLayout(STy); 3368 unsigned Elt = SL->getElementContainingOffset(IROffset); 3369 IROffset -= SL->getElementOffset(Elt); 3370 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD); 3371 } 3372 3373 // If this is an array, recurse into the field at the specified offset. 3374 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3375 llvm::Type *EltTy = ATy->getElementType(); 3376 unsigned EltSize = TD.getTypeAllocSize(EltTy); 3377 IROffset -= IROffset/EltSize*EltSize; 3378 return ContainsFloatAtOffset(EltTy, IROffset, TD); 3379 } 3380 3381 return false; 3382 } 3383 3384 3385 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the 3386 /// low 8 bytes of an XMM register, corresponding to the SSE class. 3387 llvm::Type *X86_64ABIInfo:: 3388 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3389 QualType SourceTy, unsigned SourceOffset) const { 3390 // The only three choices we have are either double, <2 x float>, or float. We 3391 // pass as float if the last 4 bytes is just padding. This happens for 3392 // structs that contain 3 floats. 3393 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32, 3394 SourceOffset*8+64, getContext())) 3395 return llvm::Type::getFloatTy(getVMContext()); 3396 3397 // We want to pass as <2 x float> if the LLVM IR type contains a float at 3398 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the 3399 // case. 3400 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) && 3401 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout())) 3402 return llvm::FixedVectorType::get(llvm::Type::getFloatTy(getVMContext()), 3403 2); 3404 3405 return llvm::Type::getDoubleTy(getVMContext()); 3406 } 3407 3408 3409 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in 3410 /// an 8-byte GPR. This means that we either have a scalar or we are talking 3411 /// about the high or low part of an up-to-16-byte struct. This routine picks 3412 /// the best LLVM IR type to represent this, which may be i64 or may be anything 3413 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, 3414 /// etc). 3415 /// 3416 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for 3417 /// the source type. IROffset is an offset in bytes into the LLVM IR type that 3418 /// the 8-byte value references. PrefType may be null. 3419 /// 3420 /// SourceTy is the source-level type for the entire argument. SourceOffset is 3421 /// an offset into this that we're processing (which is always either 0 or 8). 3422 /// 3423 llvm::Type *X86_64ABIInfo:: 3424 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3425 QualType SourceTy, unsigned SourceOffset) const { 3426 // If we're dealing with an un-offset LLVM IR type, then it means that we're 3427 // returning an 8-byte unit starting with it. See if we can safely use it. 3428 if (IROffset == 0) { 3429 // Pointers and int64's always fill the 8-byte unit. 3430 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) || 3431 IRType->isIntegerTy(64)) 3432 return IRType; 3433 3434 // If we have a 1/2/4-byte integer, we can use it only if the rest of the 3435 // goodness in the source type is just tail padding. This is allowed to 3436 // kick in for struct {double,int} on the int, but not on 3437 // struct{double,int,int} because we wouldn't return the second int. We 3438 // have to do this analysis on the source type because we can't depend on 3439 // unions being lowered a specific way etc. 3440 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || 3441 IRType->isIntegerTy(32) || 3442 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) { 3443 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 : 3444 cast<llvm::IntegerType>(IRType)->getBitWidth(); 3445 3446 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, 3447 SourceOffset*8+64, getContext())) 3448 return IRType; 3449 } 3450 } 3451 3452 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3453 // If this is a struct, recurse into the field at the specified offset. 3454 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy); 3455 if (IROffset < SL->getSizeInBytes()) { 3456 unsigned FieldIdx = SL->getElementContainingOffset(IROffset); 3457 IROffset -= SL->getElementOffset(FieldIdx); 3458 3459 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, 3460 SourceTy, SourceOffset); 3461 } 3462 } 3463 3464 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3465 llvm::Type *EltTy = ATy->getElementType(); 3466 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy); 3467 unsigned EltOffset = IROffset/EltSize*EltSize; 3468 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, 3469 SourceOffset); 3470 } 3471 3472 // Okay, we don't have any better idea of what to pass, so we pass this in an 3473 // integer register that isn't too big to fit the rest of the struct. 3474 unsigned TySizeInBytes = 3475 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); 3476 3477 assert(TySizeInBytes != SourceOffset && "Empty field?"); 3478 3479 // It is always safe to classify this as an integer type up to i64 that 3480 // isn't larger than the structure. 3481 return llvm::IntegerType::get(getVMContext(), 3482 std::min(TySizeInBytes-SourceOffset, 8U)*8); 3483 } 3484 3485 3486 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally 3487 /// be used as elements of a two register pair to pass or return, return a 3488 /// first class aggregate to represent them. For example, if the low part of 3489 /// a by-value argument should be passed as i32* and the high part as float, 3490 /// return {i32*, float}. 3491 static llvm::Type * 3492 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, 3493 const llvm::DataLayout &TD) { 3494 // In order to correctly satisfy the ABI, we need to the high part to start 3495 // at offset 8. If the high and low parts we inferred are both 4-byte types 3496 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have 3497 // the second element at offset 8. Check for this: 3498 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); 3499 unsigned HiAlign = TD.getABITypeAlignment(Hi); 3500 unsigned HiStart = llvm::alignTo(LoSize, HiAlign); 3501 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!"); 3502 3503 // To handle this, we have to increase the size of the low part so that the 3504 // second element will start at an 8 byte offset. We can't increase the size 3505 // of the second element because it might make us access off the end of the 3506 // struct. 3507 if (HiStart != 8) { 3508 // There are usually two sorts of types the ABI generation code can produce 3509 // for the low part of a pair that aren't 8 bytes in size: float or 3510 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and 3511 // NaCl). 3512 // Promote these to a larger type. 3513 if (Lo->isFloatTy()) 3514 Lo = llvm::Type::getDoubleTy(Lo->getContext()); 3515 else { 3516 assert((Lo->isIntegerTy() || Lo->isPointerTy()) 3517 && "Invalid/unknown lo type"); 3518 Lo = llvm::Type::getInt64Ty(Lo->getContext()); 3519 } 3520 } 3521 3522 llvm::StructType *Result = llvm::StructType::get(Lo, Hi); 3523 3524 // Verify that the second element is at an 8-byte offset. 3525 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && 3526 "Invalid x86-64 argument pair!"); 3527 return Result; 3528 } 3529 3530 ABIArgInfo X86_64ABIInfo:: 3531 classifyReturnType(QualType RetTy) const { 3532 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the 3533 // classification algorithm. 3534 X86_64ABIInfo::Class Lo, Hi; 3535 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true); 3536 3537 // Check some invariants. 3538 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3539 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3540 3541 llvm::Type *ResType = nullptr; 3542 switch (Lo) { 3543 case NoClass: 3544 if (Hi == NoClass) 3545 return ABIArgInfo::getIgnore(); 3546 // If the low part is just padding, it takes no register, leave ResType 3547 // null. 3548 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3549 "Unknown missing lo part"); 3550 break; 3551 3552 case SSEUp: 3553 case X87Up: 3554 llvm_unreachable("Invalid classification for lo word."); 3555 3556 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via 3557 // hidden argument. 3558 case Memory: 3559 return getIndirectReturnResult(RetTy); 3560 3561 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next 3562 // available register of the sequence %rax, %rdx is used. 3563 case Integer: 3564 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3565 3566 // If we have a sign or zero extended integer, make sure to return Extend 3567 // so that the parameter gets the right LLVM IR attributes. 3568 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3569 // Treat an enum type as its underlying type. 3570 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3571 RetTy = EnumTy->getDecl()->getIntegerType(); 3572 3573 if (RetTy->isIntegralOrEnumerationType() && 3574 isPromotableIntegerTypeForABI(RetTy)) 3575 return ABIArgInfo::getExtend(RetTy); 3576 } 3577 break; 3578 3579 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next 3580 // available SSE register of the sequence %xmm0, %xmm1 is used. 3581 case SSE: 3582 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3583 break; 3584 3585 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is 3586 // returned on the X87 stack in %st0 as 80-bit x87 number. 3587 case X87: 3588 ResType = llvm::Type::getX86_FP80Ty(getVMContext()); 3589 break; 3590 3591 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real 3592 // part of the value is returned in %st0 and the imaginary part in 3593 // %st1. 3594 case ComplexX87: 3595 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); 3596 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), 3597 llvm::Type::getX86_FP80Ty(getVMContext())); 3598 break; 3599 } 3600 3601 llvm::Type *HighPart = nullptr; 3602 switch (Hi) { 3603 // Memory was handled previously and X87 should 3604 // never occur as a hi class. 3605 case Memory: 3606 case X87: 3607 llvm_unreachable("Invalid classification for hi word."); 3608 3609 case ComplexX87: // Previously handled. 3610 case NoClass: 3611 break; 3612 3613 case Integer: 3614 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3615 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3616 return ABIArgInfo::getDirect(HighPart, 8); 3617 break; 3618 case SSE: 3619 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3620 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3621 return ABIArgInfo::getDirect(HighPart, 8); 3622 break; 3623 3624 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte 3625 // is passed in the next available eightbyte chunk if the last used 3626 // vector register. 3627 // 3628 // SSEUP should always be preceded by SSE, just widen. 3629 case SSEUp: 3630 assert(Lo == SSE && "Unexpected SSEUp classification."); 3631 ResType = GetByteVectorType(RetTy); 3632 break; 3633 3634 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is 3635 // returned together with the previous X87 value in %st0. 3636 case X87Up: 3637 // If X87Up is preceded by X87, we don't need to do 3638 // anything. However, in some cases with unions it may not be 3639 // preceded by X87. In such situations we follow gcc and pass the 3640 // extra bits in an SSE reg. 3641 if (Lo != X87) { 3642 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3643 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3644 return ABIArgInfo::getDirect(HighPart, 8); 3645 } 3646 break; 3647 } 3648 3649 // If a high part was specified, merge it together with the low part. It is 3650 // known to pass in the high eightbyte of the result. We do this by forming a 3651 // first class struct aggregate with the high and low part: {low, high} 3652 if (HighPart) 3653 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3654 3655 return ABIArgInfo::getDirect(ResType); 3656 } 3657 3658 ABIArgInfo X86_64ABIInfo::classifyArgumentType( 3659 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE, 3660 bool isNamedArg) 3661 const 3662 { 3663 Ty = useFirstFieldIfTransparentUnion(Ty); 3664 3665 X86_64ABIInfo::Class Lo, Hi; 3666 classify(Ty, 0, Lo, Hi, isNamedArg); 3667 3668 // Check some invariants. 3669 // FIXME: Enforce these by construction. 3670 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3671 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3672 3673 neededInt = 0; 3674 neededSSE = 0; 3675 llvm::Type *ResType = nullptr; 3676 switch (Lo) { 3677 case NoClass: 3678 if (Hi == NoClass) 3679 return ABIArgInfo::getIgnore(); 3680 // If the low part is just padding, it takes no register, leave ResType 3681 // null. 3682 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3683 "Unknown missing lo part"); 3684 break; 3685 3686 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument 3687 // on the stack. 3688 case Memory: 3689 3690 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or 3691 // COMPLEX_X87, it is passed in memory. 3692 case X87: 3693 case ComplexX87: 3694 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect) 3695 ++neededInt; 3696 return getIndirectResult(Ty, freeIntRegs); 3697 3698 case SSEUp: 3699 case X87Up: 3700 llvm_unreachable("Invalid classification for lo word."); 3701 3702 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next 3703 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 3704 // and %r9 is used. 3705 case Integer: 3706 ++neededInt; 3707 3708 // Pick an 8-byte type based on the preferred type. 3709 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); 3710 3711 // If we have a sign or zero extended integer, make sure to return Extend 3712 // so that the parameter gets the right LLVM IR attributes. 3713 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3714 // Treat an enum type as its underlying type. 3715 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3716 Ty = EnumTy->getDecl()->getIntegerType(); 3717 3718 if (Ty->isIntegralOrEnumerationType() && 3719 isPromotableIntegerTypeForABI(Ty)) 3720 return ABIArgInfo::getExtend(Ty); 3721 } 3722 3723 break; 3724 3725 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next 3726 // available SSE register is used, the registers are taken in the 3727 // order from %xmm0 to %xmm7. 3728 case SSE: { 3729 llvm::Type *IRType = CGT.ConvertType(Ty); 3730 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); 3731 ++neededSSE; 3732 break; 3733 } 3734 } 3735 3736 llvm::Type *HighPart = nullptr; 3737 switch (Hi) { 3738 // Memory was handled previously, ComplexX87 and X87 should 3739 // never occur as hi classes, and X87Up must be preceded by X87, 3740 // which is passed in memory. 3741 case Memory: 3742 case X87: 3743 case ComplexX87: 3744 llvm_unreachable("Invalid classification for hi word."); 3745 3746 case NoClass: break; 3747 3748 case Integer: 3749 ++neededInt; 3750 // Pick an 8-byte type based on the preferred type. 3751 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3752 3753 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3754 return ABIArgInfo::getDirect(HighPart, 8); 3755 break; 3756 3757 // X87Up generally doesn't occur here (long double is passed in 3758 // memory), except in situations involving unions. 3759 case X87Up: 3760 case SSE: 3761 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3762 3763 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3764 return ABIArgInfo::getDirect(HighPart, 8); 3765 3766 ++neededSSE; 3767 break; 3768 3769 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the 3770 // eightbyte is passed in the upper half of the last used SSE 3771 // register. This only happens when 128-bit vectors are passed. 3772 case SSEUp: 3773 assert(Lo == SSE && "Unexpected SSEUp classification"); 3774 ResType = GetByteVectorType(Ty); 3775 break; 3776 } 3777 3778 // If a high part was specified, merge it together with the low part. It is 3779 // known to pass in the high eightbyte of the result. We do this by forming a 3780 // first class struct aggregate with the high and low part: {low, high} 3781 if (HighPart) 3782 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3783 3784 return ABIArgInfo::getDirect(ResType); 3785 } 3786 3787 ABIArgInfo 3788 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 3789 unsigned &NeededSSE) const { 3790 auto RT = Ty->getAs<RecordType>(); 3791 assert(RT && "classifyRegCallStructType only valid with struct types"); 3792 3793 if (RT->getDecl()->hasFlexibleArrayMember()) 3794 return getIndirectReturnResult(Ty); 3795 3796 // Sum up bases 3797 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 3798 if (CXXRD->isDynamicClass()) { 3799 NeededInt = NeededSSE = 0; 3800 return getIndirectReturnResult(Ty); 3801 } 3802 3803 for (const auto &I : CXXRD->bases()) 3804 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE) 3805 .isIndirect()) { 3806 NeededInt = NeededSSE = 0; 3807 return getIndirectReturnResult(Ty); 3808 } 3809 } 3810 3811 // Sum up members 3812 for (const auto *FD : RT->getDecl()->fields()) { 3813 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) { 3814 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE) 3815 .isIndirect()) { 3816 NeededInt = NeededSSE = 0; 3817 return getIndirectReturnResult(Ty); 3818 } 3819 } else { 3820 unsigned LocalNeededInt, LocalNeededSSE; 3821 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt, 3822 LocalNeededSSE, true) 3823 .isIndirect()) { 3824 NeededInt = NeededSSE = 0; 3825 return getIndirectReturnResult(Ty); 3826 } 3827 NeededInt += LocalNeededInt; 3828 NeededSSE += LocalNeededSSE; 3829 } 3830 } 3831 3832 return ABIArgInfo::getDirect(); 3833 } 3834 3835 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty, 3836 unsigned &NeededInt, 3837 unsigned &NeededSSE) const { 3838 3839 NeededInt = 0; 3840 NeededSSE = 0; 3841 3842 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE); 3843 } 3844 3845 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 3846 3847 const unsigned CallingConv = FI.getCallingConvention(); 3848 // It is possible to force Win64 calling convention on any x86_64 target by 3849 // using __attribute__((ms_abi)). In such case to correctly emit Win64 3850 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo. 3851 if (CallingConv == llvm::CallingConv::Win64) { 3852 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel); 3853 Win64ABIInfo.computeInfo(FI); 3854 return; 3855 } 3856 3857 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall; 3858 3859 // Keep track of the number of assigned registers. 3860 unsigned FreeIntRegs = IsRegCall ? 11 : 6; 3861 unsigned FreeSSERegs = IsRegCall ? 16 : 8; 3862 unsigned NeededInt, NeededSSE; 3863 3864 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 3865 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() && 3866 !FI.getReturnType()->getTypePtr()->isUnionType()) { 3867 FI.getReturnInfo() = 3868 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE); 3869 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3870 FreeIntRegs -= NeededInt; 3871 FreeSSERegs -= NeededSSE; 3872 } else { 3873 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3874 } 3875 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>() && 3876 getContext().getCanonicalType(FI.getReturnType() 3877 ->getAs<ComplexType>() 3878 ->getElementType()) == 3879 getContext().LongDoubleTy) 3880 // Complex Long Double Type is passed in Memory when Regcall 3881 // calling convention is used. 3882 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3883 else 3884 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 3885 } 3886 3887 // If the return value is indirect, then the hidden argument is consuming one 3888 // integer register. 3889 if (FI.getReturnInfo().isIndirect()) 3890 --FreeIntRegs; 3891 3892 // The chain argument effectively gives us another free register. 3893 if (FI.isChainCall()) 3894 ++FreeIntRegs; 3895 3896 unsigned NumRequiredArgs = FI.getNumRequiredArgs(); 3897 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers 3898 // get assigned (in left-to-right order) for passing as follows... 3899 unsigned ArgNo = 0; 3900 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3901 it != ie; ++it, ++ArgNo) { 3902 bool IsNamedArg = ArgNo < NumRequiredArgs; 3903 3904 if (IsRegCall && it->type->isStructureOrClassType()) 3905 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE); 3906 else 3907 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt, 3908 NeededSSE, IsNamedArg); 3909 3910 // AMD64-ABI 3.2.3p3: If there are no registers available for any 3911 // eightbyte of an argument, the whole argument is passed on the 3912 // stack. If registers have already been assigned for some 3913 // eightbytes of such an argument, the assignments get reverted. 3914 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3915 FreeIntRegs -= NeededInt; 3916 FreeSSERegs -= NeededSSE; 3917 } else { 3918 it->info = getIndirectResult(it->type, FreeIntRegs); 3919 } 3920 } 3921 } 3922 3923 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF, 3924 Address VAListAddr, QualType Ty) { 3925 Address overflow_arg_area_p = 3926 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); 3927 llvm::Value *overflow_arg_area = 3928 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); 3929 3930 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 3931 // byte boundary if alignment needed by type exceeds 8 byte boundary. 3932 // It isn't stated explicitly in the standard, but in practice we use 3933 // alignment greater than 16 where necessary. 3934 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 3935 if (Align > CharUnits::fromQuantity(8)) { 3936 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area, 3937 Align); 3938 } 3939 3940 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. 3941 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 3942 llvm::Value *Res = 3943 CGF.Builder.CreateBitCast(overflow_arg_area, 3944 llvm::PointerType::getUnqual(LTy)); 3945 3946 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: 3947 // l->overflow_arg_area + sizeof(type). 3948 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to 3949 // an 8 byte boundary. 3950 3951 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; 3952 llvm::Value *Offset = 3953 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); 3954 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset, 3955 "overflow_arg_area.next"); 3956 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); 3957 3958 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. 3959 return Address(Res, Align); 3960 } 3961 3962 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 3963 QualType Ty) const { 3964 // Assume that va_list type is correct; should be pointer to LLVM type: 3965 // struct { 3966 // i32 gp_offset; 3967 // i32 fp_offset; 3968 // i8* overflow_arg_area; 3969 // i8* reg_save_area; 3970 // }; 3971 unsigned neededInt, neededSSE; 3972 3973 Ty = getContext().getCanonicalType(Ty); 3974 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE, 3975 /*isNamedArg*/false); 3976 3977 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed 3978 // in the registers. If not go to step 7. 3979 if (!neededInt && !neededSSE) 3980 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 3981 3982 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of 3983 // general purpose registers needed to pass type and num_fp to hold 3984 // the number of floating point registers needed. 3985 3986 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into 3987 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or 3988 // l->fp_offset > 304 - num_fp * 16 go to step 7. 3989 // 3990 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of 3991 // register save space). 3992 3993 llvm::Value *InRegs = nullptr; 3994 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid(); 3995 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr; 3996 if (neededInt) { 3997 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); 3998 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); 3999 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); 4000 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); 4001 } 4002 4003 if (neededSSE) { 4004 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); 4005 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); 4006 llvm::Value *FitsInFP = 4007 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); 4008 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); 4009 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; 4010 } 4011 4012 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 4013 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 4014 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 4015 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 4016 4017 // Emit code to load the value if it was passed in registers. 4018 4019 CGF.EmitBlock(InRegBlock); 4020 4021 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with 4022 // an offset of l->gp_offset and/or l->fp_offset. This may require 4023 // copying to a temporary location in case the parameter is passed 4024 // in different register classes or requires an alignment greater 4025 // than 8 for general purpose registers and 16 for XMM registers. 4026 // 4027 // FIXME: This really results in shameful code when we end up needing to 4028 // collect arguments from different places; often what should result in a 4029 // simple assembling of a structure from scattered addresses has many more 4030 // loads than necessary. Can we clean this up? 4031 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 4032 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad( 4033 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area"); 4034 4035 Address RegAddr = Address::invalid(); 4036 if (neededInt && neededSSE) { 4037 // FIXME: Cleanup. 4038 assert(AI.isDirect() && "Unexpected ABI info for mixed regs"); 4039 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); 4040 Address Tmp = CGF.CreateMemTemp(Ty); 4041 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 4042 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); 4043 llvm::Type *TyLo = ST->getElementType(0); 4044 llvm::Type *TyHi = ST->getElementType(1); 4045 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && 4046 "Unexpected ABI info for mixed regs"); 4047 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); 4048 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); 4049 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset); 4050 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset); 4051 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr; 4052 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr; 4053 4054 // Copy the first element. 4055 // FIXME: Our choice of alignment here and below is probably pessimistic. 4056 llvm::Value *V = CGF.Builder.CreateAlignedLoad( 4057 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo), 4058 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo))); 4059 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 4060 4061 // Copy the second element. 4062 V = CGF.Builder.CreateAlignedLoad( 4063 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi), 4064 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi))); 4065 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 4066 4067 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 4068 } else if (neededInt) { 4069 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset), 4070 CharUnits::fromQuantity(8)); 4071 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 4072 4073 // Copy to a temporary if necessary to ensure the appropriate alignment. 4074 auto TInfo = getContext().getTypeInfoInChars(Ty); 4075 uint64_t TySize = TInfo.Width.getQuantity(); 4076 CharUnits TyAlign = TInfo.Align; 4077 4078 // Copy into a temporary if the type is more aligned than the 4079 // register save area. 4080 if (TyAlign.getQuantity() > 8) { 4081 Address Tmp = CGF.CreateMemTemp(Ty); 4082 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false); 4083 RegAddr = Tmp; 4084 } 4085 4086 } else if (neededSSE == 1) { 4087 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), 4088 CharUnits::fromQuantity(16)); 4089 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 4090 } else { 4091 assert(neededSSE == 2 && "Invalid number of needed registers!"); 4092 // SSE registers are spaced 16 bytes apart in the register save 4093 // area, we need to collect the two eightbytes together. 4094 // The ABI isn't explicit about this, but it seems reasonable 4095 // to assume that the slots are 16-byte aligned, since the stack is 4096 // naturally 16-byte aligned and the prologue is expected to store 4097 // all the SSE registers to the RSA. 4098 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), 4099 CharUnits::fromQuantity(16)); 4100 Address RegAddrHi = 4101 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo, 4102 CharUnits::fromQuantity(16)); 4103 llvm::Type *ST = AI.canHaveCoerceToType() 4104 ? AI.getCoerceToType() 4105 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy); 4106 llvm::Value *V; 4107 Address Tmp = CGF.CreateMemTemp(Ty); 4108 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 4109 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 4110 RegAddrLo, ST->getStructElementType(0))); 4111 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 4112 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 4113 RegAddrHi, ST->getStructElementType(1))); 4114 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 4115 4116 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 4117 } 4118 4119 // AMD64-ABI 3.5.7p5: Step 5. Set: 4120 // l->gp_offset = l->gp_offset + num_gp * 8 4121 // l->fp_offset = l->fp_offset + num_fp * 16. 4122 if (neededInt) { 4123 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); 4124 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), 4125 gp_offset_p); 4126 } 4127 if (neededSSE) { 4128 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); 4129 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), 4130 fp_offset_p); 4131 } 4132 CGF.EmitBranch(ContBlock); 4133 4134 // Emit code to load the value if it was passed in memory. 4135 4136 CGF.EmitBlock(InMemBlock); 4137 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 4138 4139 // Return the appropriate result. 4140 4141 CGF.EmitBlock(ContBlock); 4142 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock, 4143 "vaarg.addr"); 4144 return ResAddr; 4145 } 4146 4147 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 4148 QualType Ty) const { 4149 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 4150 CGF.getContext().getTypeInfoInChars(Ty), 4151 CharUnits::fromQuantity(8), 4152 /*allowHigherAlign*/ false); 4153 } 4154 4155 ABIArgInfo 4156 WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs, 4157 const ABIArgInfo ¤t) const { 4158 // Assumes vectorCall calling convention. 4159 const Type *Base = nullptr; 4160 uint64_t NumElts = 0; 4161 4162 if (!Ty->isBuiltinType() && !Ty->isVectorType() && 4163 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) { 4164 FreeSSERegs -= NumElts; 4165 return getDirectX86Hva(); 4166 } 4167 return current; 4168 } 4169 4170 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs, 4171 bool IsReturnType, bool IsVectorCall, 4172 bool IsRegCall) const { 4173 4174 if (Ty->isVoidType()) 4175 return ABIArgInfo::getIgnore(); 4176 4177 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4178 Ty = EnumTy->getDecl()->getIntegerType(); 4179 4180 TypeInfo Info = getContext().getTypeInfo(Ty); 4181 uint64_t Width = Info.Width; 4182 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align); 4183 4184 const RecordType *RT = Ty->getAs<RecordType>(); 4185 if (RT) { 4186 if (!IsReturnType) { 4187 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) 4188 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4189 } 4190 4191 if (RT->getDecl()->hasFlexibleArrayMember()) 4192 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4193 4194 } 4195 4196 const Type *Base = nullptr; 4197 uint64_t NumElts = 0; 4198 // vectorcall adds the concept of a homogenous vector aggregate, similar to 4199 // other targets. 4200 if ((IsVectorCall || IsRegCall) && 4201 isHomogeneousAggregate(Ty, Base, NumElts)) { 4202 if (IsRegCall) { 4203 if (FreeSSERegs >= NumElts) { 4204 FreeSSERegs -= NumElts; 4205 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType()) 4206 return ABIArgInfo::getDirect(); 4207 return ABIArgInfo::getExpand(); 4208 } 4209 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4210 } else if (IsVectorCall) { 4211 if (FreeSSERegs >= NumElts && 4212 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) { 4213 FreeSSERegs -= NumElts; 4214 return ABIArgInfo::getDirect(); 4215 } else if (IsReturnType) { 4216 return ABIArgInfo::getExpand(); 4217 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) { 4218 // HVAs are delayed and reclassified in the 2nd step. 4219 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4220 } 4221 } 4222 } 4223 4224 if (Ty->isMemberPointerType()) { 4225 // If the member pointer is represented by an LLVM int or ptr, pass it 4226 // directly. 4227 llvm::Type *LLTy = CGT.ConvertType(Ty); 4228 if (LLTy->isPointerTy() || LLTy->isIntegerTy()) 4229 return ABIArgInfo::getDirect(); 4230 } 4231 4232 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) { 4233 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4234 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4235 if (Width > 64 || !llvm::isPowerOf2_64(Width)) 4236 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 4237 4238 // Otherwise, coerce it to a small integer. 4239 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width)); 4240 } 4241 4242 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 4243 switch (BT->getKind()) { 4244 case BuiltinType::Bool: 4245 // Bool type is always extended to the ABI, other builtin types are not 4246 // extended. 4247 return ABIArgInfo::getExtend(Ty); 4248 4249 case BuiltinType::LongDouble: 4250 // Mingw64 GCC uses the old 80 bit extended precision floating point 4251 // unit. It passes them indirectly through memory. 4252 if (IsMingw64) { 4253 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 4254 if (LDF == &llvm::APFloat::x87DoubleExtended()) 4255 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4256 } 4257 break; 4258 4259 case BuiltinType::Int128: 4260 case BuiltinType::UInt128: 4261 // If it's a parameter type, the normal ABI rule is that arguments larger 4262 // than 8 bytes are passed indirectly. GCC follows it. We follow it too, 4263 // even though it isn't particularly efficient. 4264 if (!IsReturnType) 4265 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4266 4267 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that. 4268 // Clang matches them for compatibility. 4269 return ABIArgInfo::getDirect(llvm::FixedVectorType::get( 4270 llvm::Type::getInt64Ty(getVMContext()), 2)); 4271 4272 default: 4273 break; 4274 } 4275 } 4276 4277 if (Ty->isExtIntType()) { 4278 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4279 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4280 // However, non-power-of-two _ExtInts will be passed as 1,2,4 or 8 bytes 4281 // anyway as long is it fits in them, so we don't have to check the power of 4282 // 2. 4283 if (Width <= 64) 4284 return ABIArgInfo::getDirect(); 4285 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 4286 } 4287 4288 return ABIArgInfo::getDirect(); 4289 } 4290 4291 void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, 4292 unsigned FreeSSERegs, 4293 bool IsVectorCall, 4294 bool IsRegCall) const { 4295 unsigned Count = 0; 4296 for (auto &I : FI.arguments()) { 4297 // Vectorcall in x64 only permits the first 6 arguments to be passed 4298 // as XMM/YMM registers. 4299 if (Count < VectorcallMaxParamNumAsReg) 4300 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall); 4301 else { 4302 // Since these cannot be passed in registers, pretend no registers 4303 // are left. 4304 unsigned ZeroSSERegsAvail = 0; 4305 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false, 4306 IsVectorCall, IsRegCall); 4307 } 4308 ++Count; 4309 } 4310 4311 for (auto &I : FI.arguments()) { 4312 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info); 4313 } 4314 } 4315 4316 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 4317 const unsigned CC = FI.getCallingConvention(); 4318 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall; 4319 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall; 4320 4321 // If __attribute__((sysv_abi)) is in use, use the SysV argument 4322 // classification rules. 4323 if (CC == llvm::CallingConv::X86_64_SysV) { 4324 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel); 4325 SysVABIInfo.computeInfo(FI); 4326 return; 4327 } 4328 4329 unsigned FreeSSERegs = 0; 4330 if (IsVectorCall) { 4331 // We can use up to 4 SSE return registers with vectorcall. 4332 FreeSSERegs = 4; 4333 } else if (IsRegCall) { 4334 // RegCall gives us 16 SSE registers. 4335 FreeSSERegs = 16; 4336 } 4337 4338 if (!getCXXABI().classifyReturnType(FI)) 4339 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true, 4340 IsVectorCall, IsRegCall); 4341 4342 if (IsVectorCall) { 4343 // We can use up to 6 SSE register parameters with vectorcall. 4344 FreeSSERegs = 6; 4345 } else if (IsRegCall) { 4346 // RegCall gives us 16 SSE registers, we can reuse the return registers. 4347 FreeSSERegs = 16; 4348 } 4349 4350 if (IsVectorCall) { 4351 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall); 4352 } else { 4353 for (auto &I : FI.arguments()) 4354 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall); 4355 } 4356 4357 } 4358 4359 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4360 QualType Ty) const { 4361 4362 bool IsIndirect = false; 4363 4364 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 4365 // not 1, 2, 4, or 8 bytes, must be passed by reference." 4366 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) { 4367 uint64_t Width = getContext().getTypeSize(Ty); 4368 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width); 4369 } 4370 4371 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 4372 CGF.getContext().getTypeInfoInChars(Ty), 4373 CharUnits::fromQuantity(8), 4374 /*allowHigherAlign*/ false); 4375 } 4376 4377 static bool PPC_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4378 llvm::Value *Address, bool Is64Bit, 4379 bool IsAIX) { 4380 // This is calculated from the LLVM and GCC tables and verified 4381 // against gcc output. AFAIK all PPC ABIs use the same encoding. 4382 4383 CodeGen::CGBuilderTy &Builder = CGF.Builder; 4384 4385 llvm::IntegerType *i8 = CGF.Int8Ty; 4386 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 4387 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 4388 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16); 4389 4390 // 0-31: r0-31, the 4-byte or 8-byte general-purpose registers 4391 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 0, 31); 4392 4393 // 32-63: fp0-31, the 8-byte floating-point registers 4394 AssignToArrayRange(Builder, Address, Eight8, 32, 63); 4395 4396 // 64-67 are various 4-byte or 8-byte special-purpose registers: 4397 // 64: mq 4398 // 65: lr 4399 // 66: ctr 4400 // 67: ap 4401 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 64, 67); 4402 4403 // 68-76 are various 4-byte special-purpose registers: 4404 // 68-75 cr0-7 4405 // 76: xer 4406 AssignToArrayRange(Builder, Address, Four8, 68, 76); 4407 4408 // 77-108: v0-31, the 16-byte vector registers 4409 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108); 4410 4411 // 109: vrsave 4412 // 110: vscr 4413 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 109, 110); 4414 4415 // AIX does not utilize the rest of the registers. 4416 if (IsAIX) 4417 return false; 4418 4419 // 111: spe_acc 4420 // 112: spefscr 4421 // 113: sfp 4422 AssignToArrayRange(Builder, Address, Is64Bit ? Eight8 : Four8, 111, 113); 4423 4424 if (!Is64Bit) 4425 return false; 4426 4427 // TODO: Need to verify if these registers are used on 64 bit AIX with Power8 4428 // or above CPU. 4429 // 64-bit only registers: 4430 // 114: tfhar 4431 // 115: tfiar 4432 // 116: texasr 4433 AssignToArrayRange(Builder, Address, Eight8, 114, 116); 4434 4435 return false; 4436 } 4437 4438 // AIX 4439 namespace { 4440 /// AIXABIInfo - The AIX XCOFF ABI information. 4441 class AIXABIInfo : public ABIInfo { 4442 const bool Is64Bit; 4443 const unsigned PtrByteSize; 4444 CharUnits getParamTypeAlignment(QualType Ty) const; 4445 4446 public: 4447 AIXABIInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit) 4448 : ABIInfo(CGT), Is64Bit(Is64Bit), PtrByteSize(Is64Bit ? 8 : 4) {} 4449 4450 bool isPromotableTypeForABI(QualType Ty) const; 4451 4452 ABIArgInfo classifyReturnType(QualType RetTy) const; 4453 ABIArgInfo classifyArgumentType(QualType Ty) const; 4454 4455 void computeInfo(CGFunctionInfo &FI) const override { 4456 if (!getCXXABI().classifyReturnType(FI)) 4457 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4458 4459 for (auto &I : FI.arguments()) 4460 I.info = classifyArgumentType(I.type); 4461 } 4462 4463 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4464 QualType Ty) const override; 4465 }; 4466 4467 class AIXTargetCodeGenInfo : public TargetCodeGenInfo { 4468 const bool Is64Bit; 4469 4470 public: 4471 AIXTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool Is64Bit) 4472 : TargetCodeGenInfo(std::make_unique<AIXABIInfo>(CGT, Is64Bit)), 4473 Is64Bit(Is64Bit) {} 4474 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4475 return 1; // r1 is the dedicated stack pointer 4476 } 4477 4478 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4479 llvm::Value *Address) const override; 4480 }; 4481 } // namespace 4482 4483 // Return true if the ABI requires Ty to be passed sign- or zero- 4484 // extended to 32/64 bits. 4485 bool AIXABIInfo::isPromotableTypeForABI(QualType Ty) const { 4486 // Treat an enum type as its underlying type. 4487 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 4488 Ty = EnumTy->getDecl()->getIntegerType(); 4489 4490 // Promotable integer types are required to be promoted by the ABI. 4491 if (Ty->isPromotableIntegerType()) 4492 return true; 4493 4494 if (!Is64Bit) 4495 return false; 4496 4497 // For 64 bit mode, in addition to the usual promotable integer types, we also 4498 // need to extend all 32-bit types, since the ABI requires promotion to 64 4499 // bits. 4500 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 4501 switch (BT->getKind()) { 4502 case BuiltinType::Int: 4503 case BuiltinType::UInt: 4504 return true; 4505 default: 4506 break; 4507 } 4508 4509 return false; 4510 } 4511 4512 ABIArgInfo AIXABIInfo::classifyReturnType(QualType RetTy) const { 4513 if (RetTy->isAnyComplexType()) 4514 return ABIArgInfo::getDirect(); 4515 4516 if (RetTy->isVectorType()) 4517 return ABIArgInfo::getDirect(); 4518 4519 if (RetTy->isVoidType()) 4520 return ABIArgInfo::getIgnore(); 4521 4522 if (isAggregateTypeForABI(RetTy)) 4523 return getNaturalAlignIndirect(RetTy); 4524 4525 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 4526 : ABIArgInfo::getDirect()); 4527 } 4528 4529 ABIArgInfo AIXABIInfo::classifyArgumentType(QualType Ty) const { 4530 Ty = useFirstFieldIfTransparentUnion(Ty); 4531 4532 if (Ty->isAnyComplexType()) 4533 return ABIArgInfo::getDirect(); 4534 4535 if (Ty->isVectorType()) 4536 return ABIArgInfo::getDirect(); 4537 4538 if (isAggregateTypeForABI(Ty)) { 4539 // Records with non-trivial destructors/copy-constructors should not be 4540 // passed by value. 4541 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 4542 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 4543 4544 CharUnits CCAlign = getParamTypeAlignment(Ty); 4545 CharUnits TyAlign = getContext().getTypeAlignInChars(Ty); 4546 4547 return ABIArgInfo::getIndirect(CCAlign, /*ByVal*/ true, 4548 /*Realign*/ TyAlign > CCAlign); 4549 } 4550 4551 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 4552 : ABIArgInfo::getDirect()); 4553 } 4554 4555 CharUnits AIXABIInfo::getParamTypeAlignment(QualType Ty) const { 4556 // Complex types are passed just like their elements. 4557 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4558 Ty = CTy->getElementType(); 4559 4560 if (Ty->isVectorType()) 4561 return CharUnits::fromQuantity(16); 4562 4563 // If the structure contains a vector type, the alignment is 16. 4564 if (isRecordWithSIMDVectorType(getContext(), Ty)) 4565 return CharUnits::fromQuantity(16); 4566 4567 return CharUnits::fromQuantity(PtrByteSize); 4568 } 4569 4570 Address AIXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4571 QualType Ty) const { 4572 if (Ty->isAnyComplexType()) 4573 llvm::report_fatal_error("complex type is not supported on AIX yet"); 4574 4575 if (Ty->isVectorType()) 4576 llvm::report_fatal_error( 4577 "vector types are not yet supported for variadic functions on AIX"); 4578 4579 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 4580 TypeInfo.Align = getParamTypeAlignment(Ty); 4581 4582 CharUnits SlotSize = CharUnits::fromQuantity(PtrByteSize); 4583 4584 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, TypeInfo, 4585 SlotSize, /*AllowHigher*/ true); 4586 } 4587 4588 bool AIXTargetCodeGenInfo::initDwarfEHRegSizeTable( 4589 CodeGen::CodeGenFunction &CGF, llvm::Value *Address) const { 4590 return PPC_initDwarfEHRegSizeTable(CGF, Address, Is64Bit, /*IsAIX*/ true); 4591 } 4592 4593 // PowerPC-32 4594 namespace { 4595 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information. 4596 class PPC32_SVR4_ABIInfo : public DefaultABIInfo { 4597 bool IsSoftFloatABI; 4598 bool IsRetSmallStructInRegABI; 4599 4600 CharUnits getParamTypeAlignment(QualType Ty) const; 4601 4602 public: 4603 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI, 4604 bool RetSmallStructInRegABI) 4605 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI), 4606 IsRetSmallStructInRegABI(RetSmallStructInRegABI) {} 4607 4608 ABIArgInfo classifyReturnType(QualType RetTy) const; 4609 4610 void computeInfo(CGFunctionInfo &FI) const override { 4611 if (!getCXXABI().classifyReturnType(FI)) 4612 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4613 for (auto &I : FI.arguments()) 4614 I.info = classifyArgumentType(I.type); 4615 } 4616 4617 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4618 QualType Ty) const override; 4619 }; 4620 4621 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo { 4622 public: 4623 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI, 4624 bool RetSmallStructInRegABI) 4625 : TargetCodeGenInfo(std::make_unique<PPC32_SVR4_ABIInfo>( 4626 CGT, SoftFloatABI, RetSmallStructInRegABI)) {} 4627 4628 static bool isStructReturnInRegABI(const llvm::Triple &Triple, 4629 const CodeGenOptions &Opts); 4630 4631 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4632 // This is recovered from gcc output. 4633 return 1; // r1 is the dedicated stack pointer 4634 } 4635 4636 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4637 llvm::Value *Address) const override; 4638 }; 4639 } 4640 4641 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 4642 // Complex types are passed just like their elements. 4643 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 4644 Ty = CTy->getElementType(); 4645 4646 if (Ty->isVectorType()) 4647 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 4648 : 4); 4649 4650 // For single-element float/vector structs, we consider the whole type 4651 // to have the same alignment requirements as its single element. 4652 const Type *AlignTy = nullptr; 4653 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) { 4654 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 4655 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) || 4656 (BT && BT->isFloatingPoint())) 4657 AlignTy = EltType; 4658 } 4659 4660 if (AlignTy) 4661 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4); 4662 return CharUnits::fromQuantity(4); 4663 } 4664 4665 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 4666 uint64_t Size; 4667 4668 // -msvr4-struct-return puts small aggregates in GPR3 and GPR4. 4669 if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI && 4670 (Size = getContext().getTypeSize(RetTy)) <= 64) { 4671 // System V ABI (1995), page 3-22, specified: 4672 // > A structure or union whose size is less than or equal to 8 bytes 4673 // > shall be returned in r3 and r4, as if it were first stored in the 4674 // > 8-byte aligned memory area and then the low addressed word were 4675 // > loaded into r3 and the high-addressed word into r4. Bits beyond 4676 // > the last member of the structure or union are not defined. 4677 // 4678 // GCC for big-endian PPC32 inserts the pad before the first member, 4679 // not "beyond the last member" of the struct. To stay compatible 4680 // with GCC, we coerce the struct to an integer of the same size. 4681 // LLVM will extend it and return i32 in r3, or i64 in r3:r4. 4682 if (Size == 0) 4683 return ABIArgInfo::getIgnore(); 4684 else { 4685 llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size); 4686 return ABIArgInfo::getDirect(CoerceTy); 4687 } 4688 } 4689 4690 return DefaultABIInfo::classifyReturnType(RetTy); 4691 } 4692 4693 // TODO: this implementation is now likely redundant with 4694 // DefaultABIInfo::EmitVAArg. 4695 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList, 4696 QualType Ty) const { 4697 if (getTarget().getTriple().isOSDarwin()) { 4698 auto TI = getContext().getTypeInfoInChars(Ty); 4699 TI.Align = getParamTypeAlignment(Ty); 4700 4701 CharUnits SlotSize = CharUnits::fromQuantity(4); 4702 return emitVoidPtrVAArg(CGF, VAList, Ty, 4703 classifyArgumentType(Ty).isIndirect(), TI, SlotSize, 4704 /*AllowHigherAlign=*/true); 4705 } 4706 4707 const unsigned OverflowLimit = 8; 4708 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 4709 // TODO: Implement this. For now ignore. 4710 (void)CTy; 4711 return Address::invalid(); // FIXME? 4712 } 4713 4714 // struct __va_list_tag { 4715 // unsigned char gpr; 4716 // unsigned char fpr; 4717 // unsigned short reserved; 4718 // void *overflow_arg_area; 4719 // void *reg_save_area; 4720 // }; 4721 4722 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64; 4723 bool isInt = 4724 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType(); 4725 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64; 4726 4727 // All aggregates are passed indirectly? That doesn't seem consistent 4728 // with the argument-lowering code. 4729 bool isIndirect = Ty->isAggregateType(); 4730 4731 CGBuilderTy &Builder = CGF.Builder; 4732 4733 // The calling convention either uses 1-2 GPRs or 1 FPR. 4734 Address NumRegsAddr = Address::invalid(); 4735 if (isInt || IsSoftFloatABI) { 4736 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr"); 4737 } else { 4738 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr"); 4739 } 4740 4741 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs"); 4742 4743 // "Align" the register count when TY is i64. 4744 if (isI64 || (isF64 && IsSoftFloatABI)) { 4745 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1)); 4746 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U)); 4747 } 4748 4749 llvm::Value *CC = 4750 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond"); 4751 4752 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs"); 4753 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow"); 4754 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont"); 4755 4756 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow); 4757 4758 llvm::Type *DirectTy = CGF.ConvertType(Ty); 4759 if (isIndirect) DirectTy = DirectTy->getPointerTo(0); 4760 4761 // Case 1: consume registers. 4762 Address RegAddr = Address::invalid(); 4763 { 4764 CGF.EmitBlock(UsingRegs); 4765 4766 Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4); 4767 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr), 4768 CharUnits::fromQuantity(8)); 4769 assert(RegAddr.getElementType() == CGF.Int8Ty); 4770 4771 // Floating-point registers start after the general-purpose registers. 4772 if (!(isInt || IsSoftFloatABI)) { 4773 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr, 4774 CharUnits::fromQuantity(32)); 4775 } 4776 4777 // Get the address of the saved value by scaling the number of 4778 // registers we've used by the number of 4779 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8); 4780 llvm::Value *RegOffset = 4781 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity())); 4782 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty, 4783 RegAddr.getPointer(), RegOffset), 4784 RegAddr.getAlignment().alignmentOfArrayElement(RegSize)); 4785 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy); 4786 4787 // Increase the used-register count. 4788 NumRegs = 4789 Builder.CreateAdd(NumRegs, 4790 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1)); 4791 Builder.CreateStore(NumRegs, NumRegsAddr); 4792 4793 CGF.EmitBranch(Cont); 4794 } 4795 4796 // Case 2: consume space in the overflow area. 4797 Address MemAddr = Address::invalid(); 4798 { 4799 CGF.EmitBlock(UsingOverflow); 4800 4801 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr); 4802 4803 // Everything in the overflow area is rounded up to a size of at least 4. 4804 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4); 4805 4806 CharUnits Size; 4807 if (!isIndirect) { 4808 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty); 4809 Size = TypeInfo.Width.alignTo(OverflowAreaAlign); 4810 } else { 4811 Size = CGF.getPointerSize(); 4812 } 4813 4814 Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3); 4815 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"), 4816 OverflowAreaAlign); 4817 // Round up address of argument to alignment 4818 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 4819 if (Align > OverflowAreaAlign) { 4820 llvm::Value *Ptr = OverflowArea.getPointer(); 4821 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align), 4822 Align); 4823 } 4824 4825 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy); 4826 4827 // Increase the overflow area. 4828 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size); 4829 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr); 4830 CGF.EmitBranch(Cont); 4831 } 4832 4833 CGF.EmitBlock(Cont); 4834 4835 // Merge the cases with a phi. 4836 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow, 4837 "vaarg.addr"); 4838 4839 // Load the pointer if the argument was passed indirectly. 4840 if (isIndirect) { 4841 Result = Address(Builder.CreateLoad(Result, "aggr"), 4842 getContext().getTypeAlignInChars(Ty)); 4843 } 4844 4845 return Result; 4846 } 4847 4848 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI( 4849 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 4850 assert(Triple.getArch() == llvm::Triple::ppc); 4851 4852 switch (Opts.getStructReturnConvention()) { 4853 case CodeGenOptions::SRCK_Default: 4854 break; 4855 case CodeGenOptions::SRCK_OnStack: // -maix-struct-return 4856 return false; 4857 case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return 4858 return true; 4859 } 4860 4861 if (Triple.isOSBinFormatELF() && !Triple.isOSLinux()) 4862 return true; 4863 4864 return false; 4865 } 4866 4867 bool 4868 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4869 llvm::Value *Address) const { 4870 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ false, 4871 /*IsAIX*/ false); 4872 } 4873 4874 // PowerPC-64 4875 4876 namespace { 4877 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information. 4878 class PPC64_SVR4_ABIInfo : public SwiftABIInfo { 4879 public: 4880 enum ABIKind { 4881 ELFv1 = 0, 4882 ELFv2 4883 }; 4884 4885 private: 4886 static const unsigned GPRBits = 64; 4887 ABIKind Kind; 4888 bool HasQPX; 4889 bool IsSoftFloatABI; 4890 4891 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and 4892 // will be passed in a QPX register. 4893 bool IsQPXVectorTy(const Type *Ty) const { 4894 if (!HasQPX) 4895 return false; 4896 4897 if (const VectorType *VT = Ty->getAs<VectorType>()) { 4898 unsigned NumElements = VT->getNumElements(); 4899 if (NumElements == 1) 4900 return false; 4901 4902 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) { 4903 if (getContext().getTypeSize(Ty) <= 256) 4904 return true; 4905 } else if (VT->getElementType()-> 4906 isSpecificBuiltinType(BuiltinType::Float)) { 4907 if (getContext().getTypeSize(Ty) <= 128) 4908 return true; 4909 } 4910 } 4911 4912 return false; 4913 } 4914 4915 bool IsQPXVectorTy(QualType Ty) const { 4916 return IsQPXVectorTy(Ty.getTypePtr()); 4917 } 4918 4919 public: 4920 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX, 4921 bool SoftFloatABI) 4922 : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX), 4923 IsSoftFloatABI(SoftFloatABI) {} 4924 4925 bool isPromotableTypeForABI(QualType Ty) const; 4926 CharUnits getParamTypeAlignment(QualType Ty) const; 4927 4928 ABIArgInfo classifyReturnType(QualType RetTy) const; 4929 ABIArgInfo classifyArgumentType(QualType Ty) const; 4930 4931 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 4932 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 4933 uint64_t Members) const override; 4934 4935 // TODO: We can add more logic to computeInfo to improve performance. 4936 // Example: For aggregate arguments that fit in a register, we could 4937 // use getDirectInReg (as is done below for structs containing a single 4938 // floating-point value) to avoid pushing them to memory on function 4939 // entry. This would require changing the logic in PPCISelLowering 4940 // when lowering the parameters in the caller and args in the callee. 4941 void computeInfo(CGFunctionInfo &FI) const override { 4942 if (!getCXXABI().classifyReturnType(FI)) 4943 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 4944 for (auto &I : FI.arguments()) { 4945 // We rely on the default argument classification for the most part. 4946 // One exception: An aggregate containing a single floating-point 4947 // or vector item must be passed in a register if one is available. 4948 const Type *T = isSingleElementStruct(I.type, getContext()); 4949 if (T) { 4950 const BuiltinType *BT = T->getAs<BuiltinType>(); 4951 if (IsQPXVectorTy(T) || 4952 (T->isVectorType() && getContext().getTypeSize(T) == 128) || 4953 (BT && BT->isFloatingPoint())) { 4954 QualType QT(T, 0); 4955 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT)); 4956 continue; 4957 } 4958 } 4959 I.info = classifyArgumentType(I.type); 4960 } 4961 } 4962 4963 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 4964 QualType Ty) const override; 4965 4966 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 4967 bool asReturnValue) const override { 4968 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 4969 } 4970 4971 bool isSwiftErrorInRegister() const override { 4972 return false; 4973 } 4974 }; 4975 4976 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo { 4977 4978 public: 4979 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT, 4980 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX, 4981 bool SoftFloatABI) 4982 : TargetCodeGenInfo(std::make_unique<PPC64_SVR4_ABIInfo>( 4983 CGT, Kind, HasQPX, SoftFloatABI)) {} 4984 4985 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4986 // This is recovered from gcc output. 4987 return 1; // r1 is the dedicated stack pointer 4988 } 4989 4990 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 4991 llvm::Value *Address) const override; 4992 }; 4993 4994 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo { 4995 public: 4996 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {} 4997 4998 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 4999 // This is recovered from gcc output. 5000 return 1; // r1 is the dedicated stack pointer 5001 } 5002 5003 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5004 llvm::Value *Address) const override; 5005 }; 5006 5007 } 5008 5009 // Return true if the ABI requires Ty to be passed sign- or zero- 5010 // extended to 64 bits. 5011 bool 5012 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const { 5013 // Treat an enum type as its underlying type. 5014 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5015 Ty = EnumTy->getDecl()->getIntegerType(); 5016 5017 // Promotable integer types are required to be promoted by the ABI. 5018 if (isPromotableIntegerTypeForABI(Ty)) 5019 return true; 5020 5021 // In addition to the usual promotable integer types, we also need to 5022 // extend all 32-bit types, since the ABI requires promotion to 64 bits. 5023 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 5024 switch (BT->getKind()) { 5025 case BuiltinType::Int: 5026 case BuiltinType::UInt: 5027 return true; 5028 default: 5029 break; 5030 } 5031 5032 if (const auto *EIT = Ty->getAs<ExtIntType>()) 5033 if (EIT->getNumBits() < 64) 5034 return true; 5035 5036 return false; 5037 } 5038 5039 /// isAlignedParamType - Determine whether a type requires 16-byte or 5040 /// higher alignment in the parameter area. Always returns at least 8. 5041 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const { 5042 // Complex types are passed just like their elements. 5043 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 5044 Ty = CTy->getElementType(); 5045 5046 // Only vector types of size 16 bytes need alignment (larger types are 5047 // passed via reference, smaller types are not aligned). 5048 if (IsQPXVectorTy(Ty)) { 5049 if (getContext().getTypeSize(Ty) > 128) 5050 return CharUnits::fromQuantity(32); 5051 5052 return CharUnits::fromQuantity(16); 5053 } else if (Ty->isVectorType()) { 5054 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8); 5055 } else if (Ty->isRealFloatingType() && getContext().getTypeSize(Ty) == 128) { 5056 // IEEE 128-bit floating numbers are also stored in vector registers. 5057 // And both IEEE quad-precision and IBM extended double (ppc_fp128) should 5058 // be quad-word aligned. 5059 return CharUnits::fromQuantity(16); 5060 } 5061 5062 // For single-element float/vector structs, we consider the whole type 5063 // to have the same alignment requirements as its single element. 5064 const Type *AlignAsType = nullptr; 5065 const Type *EltType = isSingleElementStruct(Ty, getContext()); 5066 if (EltType) { 5067 const BuiltinType *BT = EltType->getAs<BuiltinType>(); 5068 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() && 5069 getContext().getTypeSize(EltType) == 128) || 5070 (BT && BT->isFloatingPoint())) 5071 AlignAsType = EltType; 5072 } 5073 5074 // Likewise for ELFv2 homogeneous aggregates. 5075 const Type *Base = nullptr; 5076 uint64_t Members = 0; 5077 if (!AlignAsType && Kind == ELFv2 && 5078 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members)) 5079 AlignAsType = Base; 5080 5081 // With special case aggregates, only vector base types need alignment. 5082 if (AlignAsType && IsQPXVectorTy(AlignAsType)) { 5083 if (getContext().getTypeSize(AlignAsType) > 128) 5084 return CharUnits::fromQuantity(32); 5085 5086 return CharUnits::fromQuantity(16); 5087 } else if (AlignAsType) { 5088 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8); 5089 } 5090 5091 // Otherwise, we only need alignment for any aggregate type that 5092 // has an alignment requirement of >= 16 bytes. 5093 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) { 5094 if (HasQPX && getContext().getTypeAlign(Ty) >= 256) 5095 return CharUnits::fromQuantity(32); 5096 return CharUnits::fromQuantity(16); 5097 } 5098 5099 return CharUnits::fromQuantity(8); 5100 } 5101 5102 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous 5103 /// aggregate. Base is set to the base element type, and Members is set 5104 /// to the number of base elements. 5105 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base, 5106 uint64_t &Members) const { 5107 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 5108 uint64_t NElements = AT->getSize().getZExtValue(); 5109 if (NElements == 0) 5110 return false; 5111 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members)) 5112 return false; 5113 Members *= NElements; 5114 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 5115 const RecordDecl *RD = RT->getDecl(); 5116 if (RD->hasFlexibleArrayMember()) 5117 return false; 5118 5119 Members = 0; 5120 5121 // If this is a C++ record, check the bases first. 5122 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 5123 for (const auto &I : CXXRD->bases()) { 5124 // Ignore empty records. 5125 if (isEmptyRecord(getContext(), I.getType(), true)) 5126 continue; 5127 5128 uint64_t FldMembers; 5129 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers)) 5130 return false; 5131 5132 Members += FldMembers; 5133 } 5134 } 5135 5136 for (const auto *FD : RD->fields()) { 5137 // Ignore (non-zero arrays of) empty records. 5138 QualType FT = FD->getType(); 5139 while (const ConstantArrayType *AT = 5140 getContext().getAsConstantArrayType(FT)) { 5141 if (AT->getSize().getZExtValue() == 0) 5142 return false; 5143 FT = AT->getElementType(); 5144 } 5145 if (isEmptyRecord(getContext(), FT, true)) 5146 continue; 5147 5148 // For compatibility with GCC, ignore empty bitfields in C++ mode. 5149 if (getContext().getLangOpts().CPlusPlus && 5150 FD->isZeroLengthBitField(getContext())) 5151 continue; 5152 5153 uint64_t FldMembers; 5154 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers)) 5155 return false; 5156 5157 Members = (RD->isUnion() ? 5158 std::max(Members, FldMembers) : Members + FldMembers); 5159 } 5160 5161 if (!Base) 5162 return false; 5163 5164 // Ensure there is no padding. 5165 if (getContext().getTypeSize(Base) * Members != 5166 getContext().getTypeSize(Ty)) 5167 return false; 5168 } else { 5169 Members = 1; 5170 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 5171 Members = 2; 5172 Ty = CT->getElementType(); 5173 } 5174 5175 // Most ABIs only support float, double, and some vector type widths. 5176 if (!isHomogeneousAggregateBaseType(Ty)) 5177 return false; 5178 5179 // The base type must be the same for all members. Types that 5180 // agree in both total size and mode (float vs. vector) are 5181 // treated as being equivalent here. 5182 const Type *TyPtr = Ty.getTypePtr(); 5183 if (!Base) { 5184 Base = TyPtr; 5185 // If it's a non-power-of-2 vector, its size is already a power-of-2, 5186 // so make sure to widen it explicitly. 5187 if (const VectorType *VT = Base->getAs<VectorType>()) { 5188 QualType EltTy = VT->getElementType(); 5189 unsigned NumElements = 5190 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy); 5191 Base = getContext() 5192 .getVectorType(EltTy, NumElements, VT->getVectorKind()) 5193 .getTypePtr(); 5194 } 5195 } 5196 5197 if (Base->isVectorType() != TyPtr->isVectorType() || 5198 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr)) 5199 return false; 5200 } 5201 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members); 5202 } 5203 5204 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5205 // Homogeneous aggregates for ELFv2 must have base types of float, 5206 // double, long double, or 128-bit vectors. 5207 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5208 if (BT->getKind() == BuiltinType::Float || 5209 BT->getKind() == BuiltinType::Double || 5210 BT->getKind() == BuiltinType::LongDouble || 5211 (getContext().getTargetInfo().hasFloat128Type() && 5212 (BT->getKind() == BuiltinType::Float128))) { 5213 if (IsSoftFloatABI) 5214 return false; 5215 return true; 5216 } 5217 } 5218 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5219 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty)) 5220 return true; 5221 } 5222 return false; 5223 } 5224 5225 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough( 5226 const Type *Base, uint64_t Members) const { 5227 // Vector and fp128 types require one register, other floating point types 5228 // require one or two registers depending on their size. 5229 uint32_t NumRegs = 5230 ((getContext().getTargetInfo().hasFloat128Type() && 5231 Base->isFloat128Type()) || 5232 Base->isVectorType()) ? 1 5233 : (getContext().getTypeSize(Base) + 63) / 64; 5234 5235 // Homogeneous Aggregates may occupy at most 8 registers. 5236 return Members * NumRegs <= 8; 5237 } 5238 5239 ABIArgInfo 5240 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const { 5241 Ty = useFirstFieldIfTransparentUnion(Ty); 5242 5243 if (Ty->isAnyComplexType()) 5244 return ABIArgInfo::getDirect(); 5245 5246 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes) 5247 // or via reference (larger than 16 bytes). 5248 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) { 5249 uint64_t Size = getContext().getTypeSize(Ty); 5250 if (Size > 128) 5251 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5252 else if (Size < 128) { 5253 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 5254 return ABIArgInfo::getDirect(CoerceTy); 5255 } 5256 } 5257 5258 if (const auto *EIT = Ty->getAs<ExtIntType>()) 5259 if (EIT->getNumBits() > 128) 5260 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 5261 5262 if (isAggregateTypeForABI(Ty)) { 5263 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 5264 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 5265 5266 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity(); 5267 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 5268 5269 // ELFv2 homogeneous aggregates are passed as array types. 5270 const Type *Base = nullptr; 5271 uint64_t Members = 0; 5272 if (Kind == ELFv2 && 5273 isHomogeneousAggregate(Ty, Base, Members)) { 5274 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 5275 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 5276 return ABIArgInfo::getDirect(CoerceTy); 5277 } 5278 5279 // If an aggregate may end up fully in registers, we do not 5280 // use the ByVal method, but pass the aggregate as array. 5281 // This is usually beneficial since we avoid forcing the 5282 // back-end to store the argument to memory. 5283 uint64_t Bits = getContext().getTypeSize(Ty); 5284 if (Bits > 0 && Bits <= 8 * GPRBits) { 5285 llvm::Type *CoerceTy; 5286 5287 // Types up to 8 bytes are passed as integer type (which will be 5288 // properly aligned in the argument save area doubleword). 5289 if (Bits <= GPRBits) 5290 CoerceTy = 5291 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 5292 // Larger types are passed as arrays, with the base type selected 5293 // according to the required alignment in the save area. 5294 else { 5295 uint64_t RegBits = ABIAlign * 8; 5296 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits; 5297 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits); 5298 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs); 5299 } 5300 5301 return ABIArgInfo::getDirect(CoerceTy); 5302 } 5303 5304 // All other aggregates are passed ByVal. 5305 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 5306 /*ByVal=*/true, 5307 /*Realign=*/TyAlign > ABIAlign); 5308 } 5309 5310 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 5311 : ABIArgInfo::getDirect()); 5312 } 5313 5314 ABIArgInfo 5315 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const { 5316 if (RetTy->isVoidType()) 5317 return ABIArgInfo::getIgnore(); 5318 5319 if (RetTy->isAnyComplexType()) 5320 return ABIArgInfo::getDirect(); 5321 5322 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes) 5323 // or via reference (larger than 16 bytes). 5324 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) { 5325 uint64_t Size = getContext().getTypeSize(RetTy); 5326 if (Size > 128) 5327 return getNaturalAlignIndirect(RetTy); 5328 else if (Size < 128) { 5329 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size); 5330 return ABIArgInfo::getDirect(CoerceTy); 5331 } 5332 } 5333 5334 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 5335 if (EIT->getNumBits() > 128) 5336 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 5337 5338 if (isAggregateTypeForABI(RetTy)) { 5339 // ELFv2 homogeneous aggregates are returned as array types. 5340 const Type *Base = nullptr; 5341 uint64_t Members = 0; 5342 if (Kind == ELFv2 && 5343 isHomogeneousAggregate(RetTy, Base, Members)) { 5344 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0)); 5345 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members); 5346 return ABIArgInfo::getDirect(CoerceTy); 5347 } 5348 5349 // ELFv2 small aggregates are returned in up to two registers. 5350 uint64_t Bits = getContext().getTypeSize(RetTy); 5351 if (Kind == ELFv2 && Bits <= 2 * GPRBits) { 5352 if (Bits == 0) 5353 return ABIArgInfo::getIgnore(); 5354 5355 llvm::Type *CoerceTy; 5356 if (Bits > GPRBits) { 5357 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits); 5358 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy); 5359 } else 5360 CoerceTy = 5361 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8)); 5362 return ABIArgInfo::getDirect(CoerceTy); 5363 } 5364 5365 // All other aggregates are returned indirectly. 5366 return getNaturalAlignIndirect(RetTy); 5367 } 5368 5369 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 5370 : ABIArgInfo::getDirect()); 5371 } 5372 5373 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine. 5374 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5375 QualType Ty) const { 5376 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 5377 TypeInfo.Align = getParamTypeAlignment(Ty); 5378 5379 CharUnits SlotSize = CharUnits::fromQuantity(8); 5380 5381 // If we have a complex type and the base type is smaller than 8 bytes, 5382 // the ABI calls for the real and imaginary parts to be right-adjusted 5383 // in separate doublewords. However, Clang expects us to produce a 5384 // pointer to a structure with the two parts packed tightly. So generate 5385 // loads of the real and imaginary parts relative to the va_list pointer, 5386 // and store them to a temporary structure. 5387 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) { 5388 CharUnits EltSize = TypeInfo.Width / 2; 5389 if (EltSize < SlotSize) { 5390 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty, 5391 SlotSize * 2, SlotSize, 5392 SlotSize, /*AllowHigher*/ true); 5393 5394 Address RealAddr = Addr; 5395 Address ImagAddr = RealAddr; 5396 if (CGF.CGM.getDataLayout().isBigEndian()) { 5397 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, 5398 SlotSize - EltSize); 5399 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr, 5400 2 * SlotSize - EltSize); 5401 } else { 5402 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize); 5403 } 5404 5405 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType()); 5406 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy); 5407 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy); 5408 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal"); 5409 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag"); 5410 5411 Address Temp = CGF.CreateMemTemp(Ty, "vacplx"); 5412 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty), 5413 /*init*/ true); 5414 return Temp; 5415 } 5416 } 5417 5418 // Otherwise, just use the general rule. 5419 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 5420 TypeInfo, SlotSize, /*AllowHigher*/ true); 5421 } 5422 5423 bool 5424 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable( 5425 CodeGen::CodeGenFunction &CGF, 5426 llvm::Value *Address) const { 5427 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true, 5428 /*IsAIX*/ false); 5429 } 5430 5431 bool 5432 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 5433 llvm::Value *Address) const { 5434 return PPC_initDwarfEHRegSizeTable(CGF, Address, /*Is64Bit*/ true, 5435 /*IsAIX*/ false); 5436 } 5437 5438 //===----------------------------------------------------------------------===// 5439 // AArch64 ABI Implementation 5440 //===----------------------------------------------------------------------===// 5441 5442 namespace { 5443 5444 class AArch64ABIInfo : public SwiftABIInfo { 5445 public: 5446 enum ABIKind { 5447 AAPCS = 0, 5448 DarwinPCS, 5449 Win64 5450 }; 5451 5452 private: 5453 ABIKind Kind; 5454 5455 public: 5456 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) 5457 : SwiftABIInfo(CGT), Kind(Kind) {} 5458 5459 private: 5460 ABIKind getABIKind() const { return Kind; } 5461 bool isDarwinPCS() const { return Kind == DarwinPCS; } 5462 5463 ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const; 5464 ABIArgInfo classifyArgumentType(QualType RetTy) const; 5465 ABIArgInfo coerceIllegalVector(QualType Ty) const; 5466 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 5467 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 5468 uint64_t Members) const override; 5469 5470 bool isIllegalVectorType(QualType Ty) const; 5471 5472 void computeInfo(CGFunctionInfo &FI) const override { 5473 if (!::classifyReturnType(getCXXABI(), FI, *this)) 5474 FI.getReturnInfo() = 5475 classifyReturnType(FI.getReturnType(), FI.isVariadic()); 5476 5477 for (auto &it : FI.arguments()) 5478 it.info = classifyArgumentType(it.type); 5479 } 5480 5481 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty, 5482 CodeGenFunction &CGF) const; 5483 5484 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty, 5485 CodeGenFunction &CGF) const; 5486 5487 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 5488 QualType Ty) const override { 5489 llvm::Type *BaseTy = CGF.ConvertType(Ty); 5490 if (isa<llvm::ScalableVectorType>(BaseTy)) 5491 llvm::report_fatal_error("Passing SVE types to variadic functions is " 5492 "currently not supported"); 5493 5494 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty) 5495 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF) 5496 : EmitAAPCSVAArg(VAListAddr, Ty, CGF); 5497 } 5498 5499 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 5500 QualType Ty) const override; 5501 5502 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 5503 bool asReturnValue) const override { 5504 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 5505 } 5506 bool isSwiftErrorInRegister() const override { 5507 return true; 5508 } 5509 5510 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 5511 unsigned elts) const override; 5512 5513 bool allowBFloatArgsAndRet() const override { 5514 return getTarget().hasBFloat16Type(); 5515 } 5516 }; 5517 5518 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo { 5519 public: 5520 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind) 5521 : TargetCodeGenInfo(std::make_unique<AArch64ABIInfo>(CGT, Kind)) {} 5522 5523 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 5524 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue"; 5525 } 5526 5527 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 5528 return 31; 5529 } 5530 5531 bool doesReturnSlotInterfereWithArgs() const override { return false; } 5532 5533 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5534 CodeGen::CodeGenModule &CGM) const override { 5535 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 5536 if (!FD) 5537 return; 5538 5539 const auto *TA = FD->getAttr<TargetAttr>(); 5540 if (TA == nullptr) 5541 return; 5542 5543 ParsedTargetAttr Attr = TA->parse(); 5544 if (Attr.BranchProtection.empty()) 5545 return; 5546 5547 TargetInfo::BranchProtectionInfo BPI; 5548 StringRef Error; 5549 (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection, 5550 BPI, Error); 5551 assert(Error.empty()); 5552 5553 auto *Fn = cast<llvm::Function>(GV); 5554 static const char *SignReturnAddrStr[] = {"none", "non-leaf", "all"}; 5555 Fn->addFnAttr("sign-return-address", SignReturnAddrStr[static_cast<int>(BPI.SignReturnAddr)]); 5556 5557 if (BPI.SignReturnAddr != LangOptions::SignReturnAddressScopeKind::None) { 5558 Fn->addFnAttr("sign-return-address-key", 5559 BPI.SignKey == LangOptions::SignReturnAddressKeyKind::AKey 5560 ? "a_key" 5561 : "b_key"); 5562 } 5563 5564 Fn->addFnAttr("branch-target-enforcement", 5565 BPI.BranchTargetEnforcement ? "true" : "false"); 5566 } 5567 }; 5568 5569 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo { 5570 public: 5571 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K) 5572 : AArch64TargetCodeGenInfo(CGT, K) {} 5573 5574 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 5575 CodeGen::CodeGenModule &CGM) const override; 5576 5577 void getDependentLibraryOption(llvm::StringRef Lib, 5578 llvm::SmallString<24> &Opt) const override { 5579 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 5580 } 5581 5582 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 5583 llvm::SmallString<32> &Opt) const override { 5584 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 5585 } 5586 }; 5587 5588 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes( 5589 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 5590 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 5591 if (GV->isDeclaration()) 5592 return; 5593 addStackProbeTargetAttributes(D, GV, CGM); 5594 } 5595 } 5596 5597 ABIArgInfo AArch64ABIInfo::coerceIllegalVector(QualType Ty) const { 5598 assert(Ty->isVectorType() && "expected vector type!"); 5599 5600 const auto *VT = Ty->castAs<VectorType>(); 5601 if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) { 5602 assert(VT->getElementType()->isBuiltinType() && "expected builtin type!"); 5603 assert(VT->getElementType()->castAs<BuiltinType>()->getKind() == 5604 BuiltinType::UChar && 5605 "unexpected builtin type for SVE predicate!"); 5606 return ABIArgInfo::getDirect(llvm::ScalableVectorType::get( 5607 llvm::Type::getInt1Ty(getVMContext()), 16)); 5608 } 5609 5610 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector) { 5611 assert(VT->getElementType()->isBuiltinType() && "expected builtin type!"); 5612 5613 const auto *BT = VT->getElementType()->castAs<BuiltinType>(); 5614 llvm::ScalableVectorType *ResType = nullptr; 5615 switch (BT->getKind()) { 5616 default: 5617 llvm_unreachable("unexpected builtin type for SVE vector!"); 5618 case BuiltinType::SChar: 5619 case BuiltinType::UChar: 5620 ResType = llvm::ScalableVectorType::get( 5621 llvm::Type::getInt8Ty(getVMContext()), 16); 5622 break; 5623 case BuiltinType::Short: 5624 case BuiltinType::UShort: 5625 ResType = llvm::ScalableVectorType::get( 5626 llvm::Type::getInt16Ty(getVMContext()), 8); 5627 break; 5628 case BuiltinType::Int: 5629 case BuiltinType::UInt: 5630 ResType = llvm::ScalableVectorType::get( 5631 llvm::Type::getInt32Ty(getVMContext()), 4); 5632 break; 5633 case BuiltinType::Long: 5634 case BuiltinType::ULong: 5635 ResType = llvm::ScalableVectorType::get( 5636 llvm::Type::getInt64Ty(getVMContext()), 2); 5637 break; 5638 case BuiltinType::Half: 5639 ResType = llvm::ScalableVectorType::get( 5640 llvm::Type::getHalfTy(getVMContext()), 8); 5641 break; 5642 case BuiltinType::Float: 5643 ResType = llvm::ScalableVectorType::get( 5644 llvm::Type::getFloatTy(getVMContext()), 4); 5645 break; 5646 case BuiltinType::Double: 5647 ResType = llvm::ScalableVectorType::get( 5648 llvm::Type::getDoubleTy(getVMContext()), 2); 5649 break; 5650 case BuiltinType::BFloat16: 5651 ResType = llvm::ScalableVectorType::get( 5652 llvm::Type::getBFloatTy(getVMContext()), 8); 5653 break; 5654 } 5655 return ABIArgInfo::getDirect(ResType); 5656 } 5657 5658 uint64_t Size = getContext().getTypeSize(Ty); 5659 // Android promotes <2 x i8> to i16, not i32 5660 if (isAndroid() && (Size <= 16)) { 5661 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext()); 5662 return ABIArgInfo::getDirect(ResType); 5663 } 5664 if (Size <= 32) { 5665 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext()); 5666 return ABIArgInfo::getDirect(ResType); 5667 } 5668 if (Size == 64) { 5669 auto *ResType = 5670 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2); 5671 return ABIArgInfo::getDirect(ResType); 5672 } 5673 if (Size == 128) { 5674 auto *ResType = 5675 llvm::FixedVectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4); 5676 return ABIArgInfo::getDirect(ResType); 5677 } 5678 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5679 } 5680 5681 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const { 5682 Ty = useFirstFieldIfTransparentUnion(Ty); 5683 5684 // Handle illegal vector types here. 5685 if (isIllegalVectorType(Ty)) 5686 return coerceIllegalVector(Ty); 5687 5688 if (!isAggregateTypeForABI(Ty)) { 5689 // Treat an enum type as its underlying type. 5690 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 5691 Ty = EnumTy->getDecl()->getIntegerType(); 5692 5693 if (const auto *EIT = Ty->getAs<ExtIntType>()) 5694 if (EIT->getNumBits() > 128) 5695 return getNaturalAlignIndirect(Ty); 5696 5697 return (isPromotableIntegerTypeForABI(Ty) && isDarwinPCS() 5698 ? ABIArgInfo::getExtend(Ty) 5699 : ABIArgInfo::getDirect()); 5700 } 5701 5702 // Structures with either a non-trivial destructor or a non-trivial 5703 // copy constructor are always indirect. 5704 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 5705 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 5706 CGCXXABI::RAA_DirectInMemory); 5707 } 5708 5709 // Empty records are always ignored on Darwin, but actually passed in C++ mode 5710 // elsewhere for GNU compatibility. 5711 uint64_t Size = getContext().getTypeSize(Ty); 5712 bool IsEmpty = isEmptyRecord(getContext(), Ty, true); 5713 if (IsEmpty || Size == 0) { 5714 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS()) 5715 return ABIArgInfo::getIgnore(); 5716 5717 // GNU C mode. The only argument that gets ignored is an empty one with size 5718 // 0. 5719 if (IsEmpty && Size == 0) 5720 return ABIArgInfo::getIgnore(); 5721 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 5722 } 5723 5724 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded. 5725 const Type *Base = nullptr; 5726 uint64_t Members = 0; 5727 if (isHomogeneousAggregate(Ty, Base, Members)) { 5728 return ABIArgInfo::getDirect( 5729 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members)); 5730 } 5731 5732 // Aggregates <= 16 bytes are passed directly in registers or on the stack. 5733 if (Size <= 128) { 5734 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5735 // same size and alignment. 5736 if (getTarget().isRenderScriptTarget()) { 5737 return coerceToIntArray(Ty, getContext(), getVMContext()); 5738 } 5739 unsigned Alignment; 5740 if (Kind == AArch64ABIInfo::AAPCS) { 5741 Alignment = getContext().getTypeUnadjustedAlign(Ty); 5742 Alignment = Alignment < 128 ? 64 : 128; 5743 } else { 5744 Alignment = std::max(getContext().getTypeAlign(Ty), 5745 (unsigned)getTarget().getPointerWidth(0)); 5746 } 5747 Size = llvm::alignTo(Size, Alignment); 5748 5749 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5750 // For aggregates with 16-byte alignment, we use i128. 5751 llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment); 5752 return ABIArgInfo::getDirect( 5753 Size == Alignment ? BaseTy 5754 : llvm::ArrayType::get(BaseTy, Size / Alignment)); 5755 } 5756 5757 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 5758 } 5759 5760 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy, 5761 bool IsVariadic) const { 5762 if (RetTy->isVoidType()) 5763 return ABIArgInfo::getIgnore(); 5764 5765 if (const auto *VT = RetTy->getAs<VectorType>()) { 5766 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector || 5767 VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 5768 return coerceIllegalVector(RetTy); 5769 } 5770 5771 // Large vector types should be returned via memory. 5772 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) 5773 return getNaturalAlignIndirect(RetTy); 5774 5775 if (!isAggregateTypeForABI(RetTy)) { 5776 // Treat an enum type as its underlying type. 5777 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 5778 RetTy = EnumTy->getDecl()->getIntegerType(); 5779 5780 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 5781 if (EIT->getNumBits() > 128) 5782 return getNaturalAlignIndirect(RetTy); 5783 5784 return (isPromotableIntegerTypeForABI(RetTy) && isDarwinPCS() 5785 ? ABIArgInfo::getExtend(RetTy) 5786 : ABIArgInfo::getDirect()); 5787 } 5788 5789 uint64_t Size = getContext().getTypeSize(RetTy); 5790 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0) 5791 return ABIArgInfo::getIgnore(); 5792 5793 const Type *Base = nullptr; 5794 uint64_t Members = 0; 5795 if (isHomogeneousAggregate(RetTy, Base, Members) && 5796 !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 && 5797 IsVariadic)) 5798 // Homogeneous Floating-point Aggregates (HFAs) are returned directly. 5799 return ABIArgInfo::getDirect(); 5800 5801 // Aggregates <= 16 bytes are returned directly in registers or on the stack. 5802 if (Size <= 128) { 5803 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of 5804 // same size and alignment. 5805 if (getTarget().isRenderScriptTarget()) { 5806 return coerceToIntArray(RetTy, getContext(), getVMContext()); 5807 } 5808 unsigned Alignment = getContext().getTypeAlign(RetTy); 5809 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes 5810 5811 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment. 5812 // For aggregates with 16-byte alignment, we use i128. 5813 if (Alignment < 128 && Size == 128) { 5814 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext()); 5815 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64)); 5816 } 5817 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size)); 5818 } 5819 5820 return getNaturalAlignIndirect(RetTy); 5821 } 5822 5823 /// isIllegalVectorType - check whether the vector type is legal for AArch64. 5824 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const { 5825 if (const VectorType *VT = Ty->getAs<VectorType>()) { 5826 // Check whether VT is a fixed-length SVE vector. These types are 5827 // represented as scalable vectors in function args/return and must be 5828 // coerced from fixed vectors. 5829 if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector || 5830 VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 5831 return true; 5832 5833 // Check whether VT is legal. 5834 unsigned NumElements = VT->getNumElements(); 5835 uint64_t Size = getContext().getTypeSize(VT); 5836 // NumElements should be power of 2. 5837 if (!llvm::isPowerOf2_32(NumElements)) 5838 return true; 5839 5840 // arm64_32 has to be compatible with the ARM logic here, which allows huge 5841 // vectors for some reason. 5842 llvm::Triple Triple = getTarget().getTriple(); 5843 if (Triple.getArch() == llvm::Triple::aarch64_32 && 5844 Triple.isOSBinFormatMachO()) 5845 return Size <= 32; 5846 5847 return Size != 64 && (Size != 128 || NumElements == 1); 5848 } 5849 return false; 5850 } 5851 5852 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize, 5853 llvm::Type *eltTy, 5854 unsigned elts) const { 5855 if (!llvm::isPowerOf2_32(elts)) 5856 return false; 5857 if (totalSize.getQuantity() != 8 && 5858 (totalSize.getQuantity() != 16 || elts == 1)) 5859 return false; 5860 return true; 5861 } 5862 5863 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 5864 // Homogeneous aggregates for AAPCS64 must have base types of a floating 5865 // point type or a short-vector type. This is the same as the 32-bit ABI, 5866 // but with the difference that any floating-point type is allowed, 5867 // including __fp16. 5868 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 5869 if (BT->isFloatingPoint()) 5870 return true; 5871 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 5872 unsigned VecSize = getContext().getTypeSize(VT); 5873 if (VecSize == 64 || VecSize == 128) 5874 return true; 5875 } 5876 return false; 5877 } 5878 5879 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 5880 uint64_t Members) const { 5881 return Members <= 4; 5882 } 5883 5884 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr, 5885 QualType Ty, 5886 CodeGenFunction &CGF) const { 5887 ABIArgInfo AI = classifyArgumentType(Ty); 5888 bool IsIndirect = AI.isIndirect(); 5889 5890 llvm::Type *BaseTy = CGF.ConvertType(Ty); 5891 if (IsIndirect) 5892 BaseTy = llvm::PointerType::getUnqual(BaseTy); 5893 else if (AI.getCoerceToType()) 5894 BaseTy = AI.getCoerceToType(); 5895 5896 unsigned NumRegs = 1; 5897 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) { 5898 BaseTy = ArrTy->getElementType(); 5899 NumRegs = ArrTy->getNumElements(); 5900 } 5901 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy(); 5902 5903 // The AArch64 va_list type and handling is specified in the Procedure Call 5904 // Standard, section B.4: 5905 // 5906 // struct { 5907 // void *__stack; 5908 // void *__gr_top; 5909 // void *__vr_top; 5910 // int __gr_offs; 5911 // int __vr_offs; 5912 // }; 5913 5914 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 5915 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 5916 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 5917 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 5918 5919 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 5920 CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty); 5921 5922 Address reg_offs_p = Address::invalid(); 5923 llvm::Value *reg_offs = nullptr; 5924 int reg_top_index; 5925 int RegSize = IsIndirect ? 8 : TySize.getQuantity(); 5926 if (!IsFPR) { 5927 // 3 is the field number of __gr_offs 5928 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p"); 5929 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs"); 5930 reg_top_index = 1; // field number for __gr_top 5931 RegSize = llvm::alignTo(RegSize, 8); 5932 } else { 5933 // 4 is the field number of __vr_offs. 5934 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p"); 5935 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs"); 5936 reg_top_index = 2; // field number for __vr_top 5937 RegSize = 16 * NumRegs; 5938 } 5939 5940 //======================================= 5941 // Find out where argument was passed 5942 //======================================= 5943 5944 // If reg_offs >= 0 we're already using the stack for this type of 5945 // argument. We don't want to keep updating reg_offs (in case it overflows, 5946 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves 5947 // whatever they get). 5948 llvm::Value *UsingStack = nullptr; 5949 UsingStack = CGF.Builder.CreateICmpSGE( 5950 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0)); 5951 5952 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock); 5953 5954 // Otherwise, at least some kind of argument could go in these registers, the 5955 // question is whether this particular type is too big. 5956 CGF.EmitBlock(MaybeRegBlock); 5957 5958 // Integer arguments may need to correct register alignment (for example a 5959 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we 5960 // align __gr_offs to calculate the potential address. 5961 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) { 5962 int Align = TyAlign.getQuantity(); 5963 5964 reg_offs = CGF.Builder.CreateAdd( 5965 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1), 5966 "align_regoffs"); 5967 reg_offs = CGF.Builder.CreateAnd( 5968 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align), 5969 "aligned_regoffs"); 5970 } 5971 5972 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list. 5973 // The fact that this is done unconditionally reflects the fact that 5974 // allocating an argument to the stack also uses up all the remaining 5975 // registers of the appropriate kind. 5976 llvm::Value *NewOffset = nullptr; 5977 NewOffset = CGF.Builder.CreateAdd( 5978 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs"); 5979 CGF.Builder.CreateStore(NewOffset, reg_offs_p); 5980 5981 // Now we're in a position to decide whether this argument really was in 5982 // registers or not. 5983 llvm::Value *InRegs = nullptr; 5984 InRegs = CGF.Builder.CreateICmpSLE( 5985 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg"); 5986 5987 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock); 5988 5989 //======================================= 5990 // Argument was in registers 5991 //======================================= 5992 5993 // Now we emit the code for if the argument was originally passed in 5994 // registers. First start the appropriate block: 5995 CGF.EmitBlock(InRegBlock); 5996 5997 llvm::Value *reg_top = nullptr; 5998 Address reg_top_p = 5999 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p"); 6000 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top"); 6001 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs), 6002 CharUnits::fromQuantity(IsFPR ? 16 : 8)); 6003 Address RegAddr = Address::invalid(); 6004 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty); 6005 6006 if (IsIndirect) { 6007 // If it's been passed indirectly (actually a struct), whatever we find from 6008 // stored registers or on the stack will actually be a struct **. 6009 MemTy = llvm::PointerType::getUnqual(MemTy); 6010 } 6011 6012 const Type *Base = nullptr; 6013 uint64_t NumMembers = 0; 6014 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers); 6015 if (IsHFA && NumMembers > 1) { 6016 // Homogeneous aggregates passed in registers will have their elements split 6017 // and stored 16-bytes apart regardless of size (they're notionally in qN, 6018 // qN+1, ...). We reload and store into a temporary local variable 6019 // contiguously. 6020 assert(!IsIndirect && "Homogeneous aggregates should be passed directly"); 6021 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0)); 6022 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0)); 6023 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers); 6024 Address Tmp = CGF.CreateTempAlloca(HFATy, 6025 std::max(TyAlign, BaseTyInfo.Align)); 6026 6027 // On big-endian platforms, the value will be right-aligned in its slot. 6028 int Offset = 0; 6029 if (CGF.CGM.getDataLayout().isBigEndian() && 6030 BaseTyInfo.Width.getQuantity() < 16) 6031 Offset = 16 - BaseTyInfo.Width.getQuantity(); 6032 6033 for (unsigned i = 0; i < NumMembers; ++i) { 6034 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset); 6035 Address LoadAddr = 6036 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset); 6037 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy); 6038 6039 Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i); 6040 6041 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr); 6042 CGF.Builder.CreateStore(Elem, StoreAddr); 6043 } 6044 6045 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy); 6046 } else { 6047 // Otherwise the object is contiguous in memory. 6048 6049 // It might be right-aligned in its slot. 6050 CharUnits SlotSize = BaseAddr.getAlignment(); 6051 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect && 6052 (IsHFA || !isAggregateTypeForABI(Ty)) && 6053 TySize < SlotSize) { 6054 CharUnits Offset = SlotSize - TySize; 6055 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset); 6056 } 6057 6058 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy); 6059 } 6060 6061 CGF.EmitBranch(ContBlock); 6062 6063 //======================================= 6064 // Argument was on the stack 6065 //======================================= 6066 CGF.EmitBlock(OnStackBlock); 6067 6068 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p"); 6069 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack"); 6070 6071 // Again, stack arguments may need realignment. In this case both integer and 6072 // floating-point ones might be affected. 6073 if (!IsIndirect && TyAlign.getQuantity() > 8) { 6074 int Align = TyAlign.getQuantity(); 6075 6076 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty); 6077 6078 OnStackPtr = CGF.Builder.CreateAdd( 6079 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1), 6080 "align_stack"); 6081 OnStackPtr = CGF.Builder.CreateAnd( 6082 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align), 6083 "align_stack"); 6084 6085 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy); 6086 } 6087 Address OnStackAddr(OnStackPtr, 6088 std::max(CharUnits::fromQuantity(8), TyAlign)); 6089 6090 // All stack slots are multiples of 8 bytes. 6091 CharUnits StackSlotSize = CharUnits::fromQuantity(8); 6092 CharUnits StackSize; 6093 if (IsIndirect) 6094 StackSize = StackSlotSize; 6095 else 6096 StackSize = TySize.alignTo(StackSlotSize); 6097 6098 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize); 6099 llvm::Value *NewStack = 6100 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack"); 6101 6102 // Write the new value of __stack for the next call to va_arg 6103 CGF.Builder.CreateStore(NewStack, stack_p); 6104 6105 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) && 6106 TySize < StackSlotSize) { 6107 CharUnits Offset = StackSlotSize - TySize; 6108 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset); 6109 } 6110 6111 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy); 6112 6113 CGF.EmitBranch(ContBlock); 6114 6115 //======================================= 6116 // Tidy up 6117 //======================================= 6118 CGF.EmitBlock(ContBlock); 6119 6120 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 6121 OnStackAddr, OnStackBlock, "vaargs.addr"); 6122 6123 if (IsIndirect) 6124 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"), 6125 TyAlign); 6126 6127 return ResAddr; 6128 } 6129 6130 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty, 6131 CodeGenFunction &CGF) const { 6132 // The backend's lowering doesn't support va_arg for aggregates or 6133 // illegal vector types. Lower VAArg here for these cases and use 6134 // the LLVM va_arg instruction for everything else. 6135 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty)) 6136 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 6137 6138 uint64_t PointerSize = getTarget().getPointerWidth(0) / 8; 6139 CharUnits SlotSize = CharUnits::fromQuantity(PointerSize); 6140 6141 // Empty records are ignored for parameter passing purposes. 6142 if (isEmptyRecord(getContext(), Ty, true)) { 6143 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 6144 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 6145 return Addr; 6146 } 6147 6148 // The size of the actual thing passed, which might end up just 6149 // being a pointer for indirect types. 6150 auto TyInfo = getContext().getTypeInfoInChars(Ty); 6151 6152 // Arguments bigger than 16 bytes which aren't homogeneous 6153 // aggregates should be passed indirectly. 6154 bool IsIndirect = false; 6155 if (TyInfo.Width.getQuantity() > 16) { 6156 const Type *Base = nullptr; 6157 uint64_t Members = 0; 6158 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members); 6159 } 6160 6161 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, 6162 TyInfo, SlotSize, /*AllowHigherAlign*/ true); 6163 } 6164 6165 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 6166 QualType Ty) const { 6167 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 6168 CGF.getContext().getTypeInfoInChars(Ty), 6169 CharUnits::fromQuantity(8), 6170 /*allowHigherAlign*/ false); 6171 } 6172 6173 //===----------------------------------------------------------------------===// 6174 // ARM ABI Implementation 6175 //===----------------------------------------------------------------------===// 6176 6177 namespace { 6178 6179 class ARMABIInfo : public SwiftABIInfo { 6180 public: 6181 enum ABIKind { 6182 APCS = 0, 6183 AAPCS = 1, 6184 AAPCS_VFP = 2, 6185 AAPCS16_VFP = 3, 6186 }; 6187 6188 private: 6189 ABIKind Kind; 6190 bool IsFloatABISoftFP; 6191 6192 public: 6193 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) 6194 : SwiftABIInfo(CGT), Kind(_Kind) { 6195 setCCs(); 6196 IsFloatABISoftFP = CGT.getCodeGenOpts().FloatABI == "softfp" || 6197 CGT.getCodeGenOpts().FloatABI == ""; // default 6198 } 6199 6200 bool isEABI() const { 6201 switch (getTarget().getTriple().getEnvironment()) { 6202 case llvm::Triple::Android: 6203 case llvm::Triple::EABI: 6204 case llvm::Triple::EABIHF: 6205 case llvm::Triple::GNUEABI: 6206 case llvm::Triple::GNUEABIHF: 6207 case llvm::Triple::MuslEABI: 6208 case llvm::Triple::MuslEABIHF: 6209 return true; 6210 default: 6211 return false; 6212 } 6213 } 6214 6215 bool isEABIHF() const { 6216 switch (getTarget().getTriple().getEnvironment()) { 6217 case llvm::Triple::EABIHF: 6218 case llvm::Triple::GNUEABIHF: 6219 case llvm::Triple::MuslEABIHF: 6220 return true; 6221 default: 6222 return false; 6223 } 6224 } 6225 6226 ABIKind getABIKind() const { return Kind; } 6227 6228 bool allowBFloatArgsAndRet() const override { 6229 return !IsFloatABISoftFP && getTarget().hasBFloat16Type(); 6230 } 6231 6232 private: 6233 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic, 6234 unsigned functionCallConv) const; 6235 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic, 6236 unsigned functionCallConv) const; 6237 ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base, 6238 uint64_t Members) const; 6239 ABIArgInfo coerceIllegalVector(QualType Ty) const; 6240 bool isIllegalVectorType(QualType Ty) const; 6241 bool containsAnyFP16Vectors(QualType Ty) const; 6242 6243 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 6244 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 6245 uint64_t Members) const override; 6246 6247 bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const; 6248 6249 void computeInfo(CGFunctionInfo &FI) const override; 6250 6251 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6252 QualType Ty) const override; 6253 6254 llvm::CallingConv::ID getLLVMDefaultCC() const; 6255 llvm::CallingConv::ID getABIDefaultCC() const; 6256 void setCCs(); 6257 6258 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 6259 bool asReturnValue) const override { 6260 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 6261 } 6262 bool isSwiftErrorInRegister() const override { 6263 return true; 6264 } 6265 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy, 6266 unsigned elts) const override; 6267 }; 6268 6269 class ARMTargetCodeGenInfo : public TargetCodeGenInfo { 6270 public: 6271 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 6272 : TargetCodeGenInfo(std::make_unique<ARMABIInfo>(CGT, K)) {} 6273 6274 const ARMABIInfo &getABIInfo() const { 6275 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo()); 6276 } 6277 6278 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 6279 return 13; 6280 } 6281 6282 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 6283 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue"; 6284 } 6285 6286 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 6287 llvm::Value *Address) const override { 6288 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 6289 6290 // 0-15 are the 16 integer registers. 6291 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15); 6292 return false; 6293 } 6294 6295 unsigned getSizeOfUnwindException() const override { 6296 if (getABIInfo().isEABI()) return 88; 6297 return TargetCodeGenInfo::getSizeOfUnwindException(); 6298 } 6299 6300 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6301 CodeGen::CodeGenModule &CGM) const override { 6302 if (GV->isDeclaration()) 6303 return; 6304 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 6305 if (!FD) 6306 return; 6307 6308 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>(); 6309 if (!Attr) 6310 return; 6311 6312 const char *Kind; 6313 switch (Attr->getInterrupt()) { 6314 case ARMInterruptAttr::Generic: Kind = ""; break; 6315 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break; 6316 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break; 6317 case ARMInterruptAttr::SWI: Kind = "SWI"; break; 6318 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break; 6319 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break; 6320 } 6321 6322 llvm::Function *Fn = cast<llvm::Function>(GV); 6323 6324 Fn->addFnAttr("interrupt", Kind); 6325 6326 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind(); 6327 if (ABI == ARMABIInfo::APCS) 6328 return; 6329 6330 // AAPCS guarantees that sp will be 8-byte aligned on any public interface, 6331 // however this is not necessarily true on taking any interrupt. Instruct 6332 // the backend to perform a realignment as part of the function prologue. 6333 llvm::AttrBuilder B; 6334 B.addStackAlignmentAttr(8); 6335 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 6336 } 6337 }; 6338 6339 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo { 6340 public: 6341 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K) 6342 : ARMTargetCodeGenInfo(CGT, K) {} 6343 6344 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6345 CodeGen::CodeGenModule &CGM) const override; 6346 6347 void getDependentLibraryOption(llvm::StringRef Lib, 6348 llvm::SmallString<24> &Opt) const override { 6349 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib); 6350 } 6351 6352 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value, 6353 llvm::SmallString<32> &Opt) const override { 6354 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 6355 } 6356 }; 6357 6358 void WindowsARMTargetCodeGenInfo::setTargetAttributes( 6359 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 6360 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 6361 if (GV->isDeclaration()) 6362 return; 6363 addStackProbeTargetAttributes(D, GV, CGM); 6364 } 6365 } 6366 6367 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const { 6368 if (!::classifyReturnType(getCXXABI(), FI, *this)) 6369 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(), 6370 FI.getCallingConvention()); 6371 6372 for (auto &I : FI.arguments()) 6373 I.info = classifyArgumentType(I.type, FI.isVariadic(), 6374 FI.getCallingConvention()); 6375 6376 6377 // Always honor user-specified calling convention. 6378 if (FI.getCallingConvention() != llvm::CallingConv::C) 6379 return; 6380 6381 llvm::CallingConv::ID cc = getRuntimeCC(); 6382 if (cc != llvm::CallingConv::C) 6383 FI.setEffectiveCallingConvention(cc); 6384 } 6385 6386 /// Return the default calling convention that LLVM will use. 6387 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const { 6388 // The default calling convention that LLVM will infer. 6389 if (isEABIHF() || getTarget().getTriple().isWatchABI()) 6390 return llvm::CallingConv::ARM_AAPCS_VFP; 6391 else if (isEABI()) 6392 return llvm::CallingConv::ARM_AAPCS; 6393 else 6394 return llvm::CallingConv::ARM_APCS; 6395 } 6396 6397 /// Return the calling convention that our ABI would like us to use 6398 /// as the C calling convention. 6399 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const { 6400 switch (getABIKind()) { 6401 case APCS: return llvm::CallingConv::ARM_APCS; 6402 case AAPCS: return llvm::CallingConv::ARM_AAPCS; 6403 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 6404 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 6405 } 6406 llvm_unreachable("bad ABI kind"); 6407 } 6408 6409 void ARMABIInfo::setCCs() { 6410 assert(getRuntimeCC() == llvm::CallingConv::C); 6411 6412 // Don't muddy up the IR with a ton of explicit annotations if 6413 // they'd just match what LLVM will infer from the triple. 6414 llvm::CallingConv::ID abiCC = getABIDefaultCC(); 6415 if (abiCC != getLLVMDefaultCC()) 6416 RuntimeCC = abiCC; 6417 } 6418 6419 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const { 6420 uint64_t Size = getContext().getTypeSize(Ty); 6421 if (Size <= 32) { 6422 llvm::Type *ResType = 6423 llvm::Type::getInt32Ty(getVMContext()); 6424 return ABIArgInfo::getDirect(ResType); 6425 } 6426 if (Size == 64 || Size == 128) { 6427 auto *ResType = llvm::FixedVectorType::get( 6428 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 6429 return ABIArgInfo::getDirect(ResType); 6430 } 6431 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 6432 } 6433 6434 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty, 6435 const Type *Base, 6436 uint64_t Members) const { 6437 assert(Base && "Base class should be set for homogeneous aggregate"); 6438 // Base can be a floating-point or a vector. 6439 if (const VectorType *VT = Base->getAs<VectorType>()) { 6440 // FP16 vectors should be converted to integer vectors 6441 if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) { 6442 uint64_t Size = getContext().getTypeSize(VT); 6443 auto *NewVecTy = llvm::FixedVectorType::get( 6444 llvm::Type::getInt32Ty(getVMContext()), Size / 32); 6445 llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members); 6446 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6447 } 6448 } 6449 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false); 6450 } 6451 6452 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic, 6453 unsigned functionCallConv) const { 6454 // 6.1.2.1 The following argument types are VFP CPRCs: 6455 // A single-precision floating-point type (including promoted 6456 // half-precision types); A double-precision floating-point type; 6457 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate 6458 // with a Base Type of a single- or double-precision floating-point type, 6459 // 64-bit containerized vectors or 128-bit containerized vectors with one 6460 // to four Elements. 6461 // Variadic functions should always marshal to the base standard. 6462 bool IsAAPCS_VFP = 6463 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false); 6464 6465 Ty = useFirstFieldIfTransparentUnion(Ty); 6466 6467 // Handle illegal vector types here. 6468 if (isIllegalVectorType(Ty)) 6469 return coerceIllegalVector(Ty); 6470 6471 if (!isAggregateTypeForABI(Ty)) { 6472 // Treat an enum type as its underlying type. 6473 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 6474 Ty = EnumTy->getDecl()->getIntegerType(); 6475 } 6476 6477 if (const auto *EIT = Ty->getAs<ExtIntType>()) 6478 if (EIT->getNumBits() > 64) 6479 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 6480 6481 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 6482 : ABIArgInfo::getDirect()); 6483 } 6484 6485 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 6486 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 6487 } 6488 6489 // Ignore empty records. 6490 if (isEmptyRecord(getContext(), Ty, true)) 6491 return ABIArgInfo::getIgnore(); 6492 6493 if (IsAAPCS_VFP) { 6494 // Homogeneous Aggregates need to be expanded when we can fit the aggregate 6495 // into VFP registers. 6496 const Type *Base = nullptr; 6497 uint64_t Members = 0; 6498 if (isHomogeneousAggregate(Ty, Base, Members)) 6499 return classifyHomogeneousAggregate(Ty, Base, Members); 6500 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 6501 // WatchOS does have homogeneous aggregates. Note that we intentionally use 6502 // this convention even for a variadic function: the backend will use GPRs 6503 // if needed. 6504 const Type *Base = nullptr; 6505 uint64_t Members = 0; 6506 if (isHomogeneousAggregate(Ty, Base, Members)) { 6507 assert(Base && Members <= 4 && "unexpected homogeneous aggregate"); 6508 llvm::Type *Ty = 6509 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members); 6510 return ABIArgInfo::getDirect(Ty, 0, nullptr, false); 6511 } 6512 } 6513 6514 if (getABIKind() == ARMABIInfo::AAPCS16_VFP && 6515 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) { 6516 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're 6517 // bigger than 128-bits, they get placed in space allocated by the caller, 6518 // and a pointer is passed. 6519 return ABIArgInfo::getIndirect( 6520 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false); 6521 } 6522 6523 // Support byval for ARM. 6524 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at 6525 // most 8-byte. We realign the indirect argument if type alignment is bigger 6526 // than ABI alignment. 6527 uint64_t ABIAlign = 4; 6528 uint64_t TyAlign; 6529 if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6530 getABIKind() == ARMABIInfo::AAPCS) { 6531 TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity(); 6532 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8); 6533 } else { 6534 TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity(); 6535 } 6536 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) { 6537 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval"); 6538 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign), 6539 /*ByVal=*/true, 6540 /*Realign=*/TyAlign > ABIAlign); 6541 } 6542 6543 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of 6544 // same size and alignment. 6545 if (getTarget().isRenderScriptTarget()) { 6546 return coerceToIntArray(Ty, getContext(), getVMContext()); 6547 } 6548 6549 // Otherwise, pass by coercing to a structure of the appropriate size. 6550 llvm::Type* ElemTy; 6551 unsigned SizeRegs; 6552 // FIXME: Try to match the types of the arguments more accurately where 6553 // we can. 6554 if (TyAlign <= 4) { 6555 ElemTy = llvm::Type::getInt32Ty(getVMContext()); 6556 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32; 6557 } else { 6558 ElemTy = llvm::Type::getInt64Ty(getVMContext()); 6559 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64; 6560 } 6561 6562 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs)); 6563 } 6564 6565 static bool isIntegerLikeType(QualType Ty, ASTContext &Context, 6566 llvm::LLVMContext &VMContext) { 6567 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure 6568 // is called integer-like if its size is less than or equal to one word, and 6569 // the offset of each of its addressable sub-fields is zero. 6570 6571 uint64_t Size = Context.getTypeSize(Ty); 6572 6573 // Check that the type fits in a word. 6574 if (Size > 32) 6575 return false; 6576 6577 // FIXME: Handle vector types! 6578 if (Ty->isVectorType()) 6579 return false; 6580 6581 // Float types are never treated as "integer like". 6582 if (Ty->isRealFloatingType()) 6583 return false; 6584 6585 // If this is a builtin or pointer type then it is ok. 6586 if (Ty->getAs<BuiltinType>() || Ty->isPointerType()) 6587 return true; 6588 6589 // Small complex integer types are "integer like". 6590 if (const ComplexType *CT = Ty->getAs<ComplexType>()) 6591 return isIntegerLikeType(CT->getElementType(), Context, VMContext); 6592 6593 // Single element and zero sized arrays should be allowed, by the definition 6594 // above, but they are not. 6595 6596 // Otherwise, it must be a record type. 6597 const RecordType *RT = Ty->getAs<RecordType>(); 6598 if (!RT) return false; 6599 6600 // Ignore records with flexible arrays. 6601 const RecordDecl *RD = RT->getDecl(); 6602 if (RD->hasFlexibleArrayMember()) 6603 return false; 6604 6605 // Check that all sub-fields are at offset 0, and are themselves "integer 6606 // like". 6607 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 6608 6609 bool HadField = false; 6610 unsigned idx = 0; 6611 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 6612 i != e; ++i, ++idx) { 6613 const FieldDecl *FD = *i; 6614 6615 // Bit-fields are not addressable, we only need to verify they are "integer 6616 // like". We still have to disallow a subsequent non-bitfield, for example: 6617 // struct { int : 0; int x } 6618 // is non-integer like according to gcc. 6619 if (FD->isBitField()) { 6620 if (!RD->isUnion()) 6621 HadField = true; 6622 6623 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6624 return false; 6625 6626 continue; 6627 } 6628 6629 // Check if this field is at offset 0. 6630 if (Layout.getFieldOffset(idx) != 0) 6631 return false; 6632 6633 if (!isIntegerLikeType(FD->getType(), Context, VMContext)) 6634 return false; 6635 6636 // Only allow at most one field in a structure. This doesn't match the 6637 // wording above, but follows gcc in situations with a field following an 6638 // empty structure. 6639 if (!RD->isUnion()) { 6640 if (HadField) 6641 return false; 6642 6643 HadField = true; 6644 } 6645 } 6646 6647 return true; 6648 } 6649 6650 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic, 6651 unsigned functionCallConv) const { 6652 6653 // Variadic functions should always marshal to the base standard. 6654 bool IsAAPCS_VFP = 6655 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true); 6656 6657 if (RetTy->isVoidType()) 6658 return ABIArgInfo::getIgnore(); 6659 6660 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 6661 // Large vector types should be returned via memory. 6662 if (getContext().getTypeSize(RetTy) > 128) 6663 return getNaturalAlignIndirect(RetTy); 6664 // TODO: FP16/BF16 vectors should be converted to integer vectors 6665 // This check is similar to isIllegalVectorType - refactor? 6666 if ((!getTarget().hasLegalHalfType() && 6667 (VT->getElementType()->isFloat16Type() || 6668 VT->getElementType()->isHalfType())) || 6669 (IsFloatABISoftFP && 6670 VT->getElementType()->isBFloat16Type())) 6671 return coerceIllegalVector(RetTy); 6672 } 6673 6674 if (!isAggregateTypeForABI(RetTy)) { 6675 // Treat an enum type as its underlying type. 6676 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 6677 RetTy = EnumTy->getDecl()->getIntegerType(); 6678 6679 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 6680 if (EIT->getNumBits() > 64) 6681 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 6682 6683 return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 6684 : ABIArgInfo::getDirect(); 6685 } 6686 6687 // Are we following APCS? 6688 if (getABIKind() == APCS) { 6689 if (isEmptyRecord(getContext(), RetTy, false)) 6690 return ABIArgInfo::getIgnore(); 6691 6692 // Complex types are all returned as packed integers. 6693 // 6694 // FIXME: Consider using 2 x vector types if the back end handles them 6695 // correctly. 6696 if (RetTy->isAnyComplexType()) 6697 return ABIArgInfo::getDirect(llvm::IntegerType::get( 6698 getVMContext(), getContext().getTypeSize(RetTy))); 6699 6700 // Integer like structures are returned in r0. 6701 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) { 6702 // Return in the smallest viable integer type. 6703 uint64_t Size = getContext().getTypeSize(RetTy); 6704 if (Size <= 8) 6705 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6706 if (Size <= 16) 6707 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6708 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6709 } 6710 6711 // Otherwise return in memory. 6712 return getNaturalAlignIndirect(RetTy); 6713 } 6714 6715 // Otherwise this is an AAPCS variant. 6716 6717 if (isEmptyRecord(getContext(), RetTy, true)) 6718 return ABIArgInfo::getIgnore(); 6719 6720 // Check for homogeneous aggregates with AAPCS-VFP. 6721 if (IsAAPCS_VFP) { 6722 const Type *Base = nullptr; 6723 uint64_t Members = 0; 6724 if (isHomogeneousAggregate(RetTy, Base, Members)) 6725 return classifyHomogeneousAggregate(RetTy, Base, Members); 6726 } 6727 6728 // Aggregates <= 4 bytes are returned in r0; other aggregates 6729 // are returned indirectly. 6730 uint64_t Size = getContext().getTypeSize(RetTy); 6731 if (Size <= 32) { 6732 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of 6733 // same size and alignment. 6734 if (getTarget().isRenderScriptTarget()) { 6735 return coerceToIntArray(RetTy, getContext(), getVMContext()); 6736 } 6737 if (getDataLayout().isBigEndian()) 6738 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4) 6739 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6740 6741 // Return in the smallest viable integer type. 6742 if (Size <= 8) 6743 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 6744 if (Size <= 16) 6745 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 6746 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 6747 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) { 6748 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext()); 6749 llvm::Type *CoerceTy = 6750 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32); 6751 return ABIArgInfo::getDirect(CoerceTy); 6752 } 6753 6754 return getNaturalAlignIndirect(RetTy); 6755 } 6756 6757 /// isIllegalVector - check whether Ty is an illegal vector type. 6758 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const { 6759 if (const VectorType *VT = Ty->getAs<VectorType> ()) { 6760 // On targets that don't support half, fp16 or bfloat, they are expanded 6761 // into float, and we don't want the ABI to depend on whether or not they 6762 // are supported in hardware. Thus return false to coerce vectors of these 6763 // types into integer vectors. 6764 // We do not depend on hasLegalHalfType for bfloat as it is a 6765 // separate IR type. 6766 if ((!getTarget().hasLegalHalfType() && 6767 (VT->getElementType()->isFloat16Type() || 6768 VT->getElementType()->isHalfType())) || 6769 (IsFloatABISoftFP && 6770 VT->getElementType()->isBFloat16Type())) 6771 return true; 6772 if (isAndroid()) { 6773 // Android shipped using Clang 3.1, which supported a slightly different 6774 // vector ABI. The primary differences were that 3-element vector types 6775 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path 6776 // accepts that legacy behavior for Android only. 6777 // Check whether VT is legal. 6778 unsigned NumElements = VT->getNumElements(); 6779 // NumElements should be power of 2 or equal to 3. 6780 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3) 6781 return true; 6782 } else { 6783 // Check whether VT is legal. 6784 unsigned NumElements = VT->getNumElements(); 6785 uint64_t Size = getContext().getTypeSize(VT); 6786 // NumElements should be power of 2. 6787 if (!llvm::isPowerOf2_32(NumElements)) 6788 return true; 6789 // Size should be greater than 32 bits. 6790 return Size <= 32; 6791 } 6792 } 6793 return false; 6794 } 6795 6796 /// Return true if a type contains any 16-bit floating point vectors 6797 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const { 6798 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 6799 uint64_t NElements = AT->getSize().getZExtValue(); 6800 if (NElements == 0) 6801 return false; 6802 return containsAnyFP16Vectors(AT->getElementType()); 6803 } else if (const RecordType *RT = Ty->getAs<RecordType>()) { 6804 const RecordDecl *RD = RT->getDecl(); 6805 6806 // If this is a C++ record, check the bases first. 6807 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6808 if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) { 6809 return containsAnyFP16Vectors(B.getType()); 6810 })) 6811 return true; 6812 6813 if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) { 6814 return FD && containsAnyFP16Vectors(FD->getType()); 6815 })) 6816 return true; 6817 6818 return false; 6819 } else { 6820 if (const VectorType *VT = Ty->getAs<VectorType>()) 6821 return (VT->getElementType()->isFloat16Type() || 6822 VT->getElementType()->isBFloat16Type() || 6823 VT->getElementType()->isHalfType()); 6824 return false; 6825 } 6826 } 6827 6828 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize, 6829 llvm::Type *eltTy, 6830 unsigned numElts) const { 6831 if (!llvm::isPowerOf2_32(numElts)) 6832 return false; 6833 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy); 6834 if (size > 64) 6835 return false; 6836 if (vectorSize.getQuantity() != 8 && 6837 (vectorSize.getQuantity() != 16 || numElts == 1)) 6838 return false; 6839 return true; 6840 } 6841 6842 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 6843 // Homogeneous aggregates for AAPCS-VFP must have base types of float, 6844 // double, or 64-bit or 128-bit vectors. 6845 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 6846 if (BT->getKind() == BuiltinType::Float || 6847 BT->getKind() == BuiltinType::Double || 6848 BT->getKind() == BuiltinType::LongDouble) 6849 return true; 6850 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 6851 unsigned VecSize = getContext().getTypeSize(VT); 6852 if (VecSize == 64 || VecSize == 128) 6853 return true; 6854 } 6855 return false; 6856 } 6857 6858 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base, 6859 uint64_t Members) const { 6860 return Members <= 4; 6861 } 6862 6863 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention, 6864 bool acceptHalf) const { 6865 // Give precedence to user-specified calling conventions. 6866 if (callConvention != llvm::CallingConv::C) 6867 return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP); 6868 else 6869 return (getABIKind() == AAPCS_VFP) || 6870 (acceptHalf && (getABIKind() == AAPCS16_VFP)); 6871 } 6872 6873 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6874 QualType Ty) const { 6875 CharUnits SlotSize = CharUnits::fromQuantity(4); 6876 6877 // Empty records are ignored for parameter passing purposes. 6878 if (isEmptyRecord(getContext(), Ty, true)) { 6879 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 6880 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 6881 return Addr; 6882 } 6883 6884 CharUnits TySize = getContext().getTypeSizeInChars(Ty); 6885 CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty); 6886 6887 // Use indirect if size of the illegal vector is bigger than 16 bytes. 6888 bool IsIndirect = false; 6889 const Type *Base = nullptr; 6890 uint64_t Members = 0; 6891 if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) { 6892 IsIndirect = true; 6893 6894 // ARMv7k passes structs bigger than 16 bytes indirectly, in space 6895 // allocated by the caller. 6896 } else if (TySize > CharUnits::fromQuantity(16) && 6897 getABIKind() == ARMABIInfo::AAPCS16_VFP && 6898 !isHomogeneousAggregate(Ty, Base, Members)) { 6899 IsIndirect = true; 6900 6901 // Otherwise, bound the type's ABI alignment. 6902 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for 6903 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte. 6904 // Our callers should be prepared to handle an under-aligned address. 6905 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP || 6906 getABIKind() == ARMABIInfo::AAPCS) { 6907 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 6908 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8)); 6909 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) { 6910 // ARMv7k allows type alignment up to 16 bytes. 6911 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4)); 6912 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16)); 6913 } else { 6914 TyAlignForABI = CharUnits::fromQuantity(4); 6915 } 6916 6917 TypeInfoChars TyInfo(TySize, TyAlignForABI, false); 6918 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo, 6919 SlotSize, /*AllowHigherAlign*/ true); 6920 } 6921 6922 //===----------------------------------------------------------------------===// 6923 // NVPTX ABI Implementation 6924 //===----------------------------------------------------------------------===// 6925 6926 namespace { 6927 6928 class NVPTXTargetCodeGenInfo; 6929 6930 class NVPTXABIInfo : public ABIInfo { 6931 NVPTXTargetCodeGenInfo &CGInfo; 6932 6933 public: 6934 NVPTXABIInfo(CodeGenTypes &CGT, NVPTXTargetCodeGenInfo &Info) 6935 : ABIInfo(CGT), CGInfo(Info) {} 6936 6937 ABIArgInfo classifyReturnType(QualType RetTy) const; 6938 ABIArgInfo classifyArgumentType(QualType Ty) const; 6939 6940 void computeInfo(CGFunctionInfo &FI) const override; 6941 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6942 QualType Ty) const override; 6943 bool isUnsupportedType(QualType T) const; 6944 ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, unsigned MaxSize) const; 6945 }; 6946 6947 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo { 6948 public: 6949 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT) 6950 : TargetCodeGenInfo(std::make_unique<NVPTXABIInfo>(CGT, *this)) {} 6951 6952 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6953 CodeGen::CodeGenModule &M) const override; 6954 bool shouldEmitStaticExternCAliases() const override; 6955 6956 llvm::Type *getCUDADeviceBuiltinSurfaceDeviceType() const override { 6957 // On the device side, surface reference is represented as an object handle 6958 // in 64-bit integer. 6959 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 6960 } 6961 6962 llvm::Type *getCUDADeviceBuiltinTextureDeviceType() const override { 6963 // On the device side, texture reference is represented as an object handle 6964 // in 64-bit integer. 6965 return llvm::Type::getInt64Ty(getABIInfo().getVMContext()); 6966 } 6967 6968 bool emitCUDADeviceBuiltinSurfaceDeviceCopy(CodeGenFunction &CGF, LValue Dst, 6969 LValue Src) const override { 6970 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 6971 return true; 6972 } 6973 6974 bool emitCUDADeviceBuiltinTextureDeviceCopy(CodeGenFunction &CGF, LValue Dst, 6975 LValue Src) const override { 6976 emitBuiltinSurfTexDeviceCopy(CGF, Dst, Src); 6977 return true; 6978 } 6979 6980 private: 6981 // Adds a NamedMDNode with GV, Name, and Operand as operands, and adds the 6982 // resulting MDNode to the nvvm.annotations MDNode. 6983 static void addNVVMMetadata(llvm::GlobalValue *GV, StringRef Name, 6984 int Operand); 6985 6986 static void emitBuiltinSurfTexDeviceCopy(CodeGenFunction &CGF, LValue Dst, 6987 LValue Src) { 6988 llvm::Value *Handle = nullptr; 6989 llvm::Constant *C = 6990 llvm::dyn_cast<llvm::Constant>(Src.getAddress(CGF).getPointer()); 6991 // Lookup `addrspacecast` through the constant pointer if any. 6992 if (auto *ASC = llvm::dyn_cast_or_null<llvm::AddrSpaceCastOperator>(C)) 6993 C = llvm::cast<llvm::Constant>(ASC->getPointerOperand()); 6994 if (auto *GV = llvm::dyn_cast_or_null<llvm::GlobalVariable>(C)) { 6995 // Load the handle from the specific global variable using 6996 // `nvvm.texsurf.handle.internal` intrinsic. 6997 Handle = CGF.EmitRuntimeCall( 6998 CGF.CGM.getIntrinsic(llvm::Intrinsic::nvvm_texsurf_handle_internal, 6999 {GV->getType()}), 7000 {GV}, "texsurf_handle"); 7001 } else 7002 Handle = CGF.EmitLoadOfScalar(Src, SourceLocation()); 7003 CGF.EmitStoreOfScalar(Handle, Dst); 7004 } 7005 }; 7006 7007 /// Checks if the type is unsupported directly by the current target. 7008 bool NVPTXABIInfo::isUnsupportedType(QualType T) const { 7009 ASTContext &Context = getContext(); 7010 if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type()) 7011 return true; 7012 if (!Context.getTargetInfo().hasFloat128Type() && 7013 (T->isFloat128Type() || 7014 (T->isRealFloatingType() && Context.getTypeSize(T) == 128))) 7015 return true; 7016 if (const auto *EIT = T->getAs<ExtIntType>()) 7017 return EIT->getNumBits() > 7018 (Context.getTargetInfo().hasInt128Type() ? 128U : 64U); 7019 if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() && 7020 Context.getTypeSize(T) > 64U) 7021 return true; 7022 if (const auto *AT = T->getAsArrayTypeUnsafe()) 7023 return isUnsupportedType(AT->getElementType()); 7024 const auto *RT = T->getAs<RecordType>(); 7025 if (!RT) 7026 return false; 7027 const RecordDecl *RD = RT->getDecl(); 7028 7029 // If this is a C++ record, check the bases first. 7030 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7031 for (const CXXBaseSpecifier &I : CXXRD->bases()) 7032 if (isUnsupportedType(I.getType())) 7033 return true; 7034 7035 for (const FieldDecl *I : RD->fields()) 7036 if (isUnsupportedType(I->getType())) 7037 return true; 7038 return false; 7039 } 7040 7041 /// Coerce the given type into an array with maximum allowed size of elements. 7042 ABIArgInfo NVPTXABIInfo::coerceToIntArrayWithLimit(QualType Ty, 7043 unsigned MaxSize) const { 7044 // Alignment and Size are measured in bits. 7045 const uint64_t Size = getContext().getTypeSize(Ty); 7046 const uint64_t Alignment = getContext().getTypeAlign(Ty); 7047 const unsigned Div = std::min<unsigned>(MaxSize, Alignment); 7048 llvm::Type *IntType = llvm::Type::getIntNTy(getVMContext(), Div); 7049 const uint64_t NumElements = (Size + Div - 1) / Div; 7050 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 7051 } 7052 7053 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const { 7054 if (RetTy->isVoidType()) 7055 return ABIArgInfo::getIgnore(); 7056 7057 if (getContext().getLangOpts().OpenMP && 7058 getContext().getLangOpts().OpenMPIsDevice && isUnsupportedType(RetTy)) 7059 return coerceToIntArrayWithLimit(RetTy, 64); 7060 7061 // note: this is different from default ABI 7062 if (!RetTy->isScalarType()) 7063 return ABIArgInfo::getDirect(); 7064 7065 // Treat an enum type as its underlying type. 7066 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7067 RetTy = EnumTy->getDecl()->getIntegerType(); 7068 7069 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 7070 : ABIArgInfo::getDirect()); 7071 } 7072 7073 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const { 7074 // Treat an enum type as its underlying type. 7075 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7076 Ty = EnumTy->getDecl()->getIntegerType(); 7077 7078 // Return aggregates type as indirect by value 7079 if (isAggregateTypeForABI(Ty)) { 7080 // Under CUDA device compilation, tex/surf builtin types are replaced with 7081 // object types and passed directly. 7082 if (getContext().getLangOpts().CUDAIsDevice) { 7083 if (Ty->isCUDADeviceBuiltinSurfaceType()) 7084 return ABIArgInfo::getDirect( 7085 CGInfo.getCUDADeviceBuiltinSurfaceDeviceType()); 7086 if (Ty->isCUDADeviceBuiltinTextureType()) 7087 return ABIArgInfo::getDirect( 7088 CGInfo.getCUDADeviceBuiltinTextureDeviceType()); 7089 } 7090 return getNaturalAlignIndirect(Ty, /* byval */ true); 7091 } 7092 7093 if (const auto *EIT = Ty->getAs<ExtIntType>()) { 7094 if ((EIT->getNumBits() > 128) || 7095 (!getContext().getTargetInfo().hasInt128Type() && 7096 EIT->getNumBits() > 64)) 7097 return getNaturalAlignIndirect(Ty, /* byval */ true); 7098 } 7099 7100 return (isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 7101 : ABIArgInfo::getDirect()); 7102 } 7103 7104 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const { 7105 if (!getCXXABI().classifyReturnType(FI)) 7106 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7107 for (auto &I : FI.arguments()) 7108 I.info = classifyArgumentType(I.type); 7109 7110 // Always honor user-specified calling convention. 7111 if (FI.getCallingConvention() != llvm::CallingConv::C) 7112 return; 7113 7114 FI.setEffectiveCallingConvention(getRuntimeCC()); 7115 } 7116 7117 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7118 QualType Ty) const { 7119 llvm_unreachable("NVPTX does not support varargs"); 7120 } 7121 7122 void NVPTXTargetCodeGenInfo::setTargetAttributes( 7123 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7124 if (GV->isDeclaration()) 7125 return; 7126 const VarDecl *VD = dyn_cast_or_null<VarDecl>(D); 7127 if (VD) { 7128 if (M.getLangOpts().CUDA) { 7129 if (VD->getType()->isCUDADeviceBuiltinSurfaceType()) 7130 addNVVMMetadata(GV, "surface", 1); 7131 else if (VD->getType()->isCUDADeviceBuiltinTextureType()) 7132 addNVVMMetadata(GV, "texture", 1); 7133 return; 7134 } 7135 } 7136 7137 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7138 if (!FD) return; 7139 7140 llvm::Function *F = cast<llvm::Function>(GV); 7141 7142 // Perform special handling in OpenCL mode 7143 if (M.getLangOpts().OpenCL) { 7144 // Use OpenCL function attributes to check for kernel functions 7145 // By default, all functions are device functions 7146 if (FD->hasAttr<OpenCLKernelAttr>()) { 7147 // OpenCL __kernel functions get kernel metadata 7148 // Create !{<func-ref>, metadata !"kernel", i32 1} node 7149 addNVVMMetadata(F, "kernel", 1); 7150 // And kernel functions are not subject to inlining 7151 F->addFnAttr(llvm::Attribute::NoInline); 7152 } 7153 } 7154 7155 // Perform special handling in CUDA mode. 7156 if (M.getLangOpts().CUDA) { 7157 // CUDA __global__ functions get a kernel metadata entry. Since 7158 // __global__ functions cannot be called from the device, we do not 7159 // need to set the noinline attribute. 7160 if (FD->hasAttr<CUDAGlobalAttr>()) { 7161 // Create !{<func-ref>, metadata !"kernel", i32 1} node 7162 addNVVMMetadata(F, "kernel", 1); 7163 } 7164 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) { 7165 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node 7166 llvm::APSInt MaxThreads(32); 7167 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext()); 7168 if (MaxThreads > 0) 7169 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue()); 7170 7171 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was 7172 // not specified in __launch_bounds__ or if the user specified a 0 value, 7173 // we don't have to add a PTX directive. 7174 if (Attr->getMinBlocks()) { 7175 llvm::APSInt MinBlocks(32); 7176 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext()); 7177 if (MinBlocks > 0) 7178 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node 7179 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue()); 7180 } 7181 } 7182 } 7183 } 7184 7185 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::GlobalValue *GV, 7186 StringRef Name, int Operand) { 7187 llvm::Module *M = GV->getParent(); 7188 llvm::LLVMContext &Ctx = M->getContext(); 7189 7190 // Get "nvvm.annotations" metadata node 7191 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); 7192 7193 llvm::Metadata *MDVals[] = { 7194 llvm::ConstantAsMetadata::get(GV), llvm::MDString::get(Ctx, Name), 7195 llvm::ConstantAsMetadata::get( 7196 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))}; 7197 // Append metadata to nvvm.annotations 7198 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 7199 } 7200 7201 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 7202 return false; 7203 } 7204 } 7205 7206 //===----------------------------------------------------------------------===// 7207 // SystemZ ABI Implementation 7208 //===----------------------------------------------------------------------===// 7209 7210 namespace { 7211 7212 class SystemZABIInfo : public SwiftABIInfo { 7213 bool HasVector; 7214 bool IsSoftFloatABI; 7215 7216 public: 7217 SystemZABIInfo(CodeGenTypes &CGT, bool HV, bool SF) 7218 : SwiftABIInfo(CGT), HasVector(HV), IsSoftFloatABI(SF) {} 7219 7220 bool isPromotableIntegerTypeForABI(QualType Ty) const; 7221 bool isCompoundType(QualType Ty) const; 7222 bool isVectorArgumentType(QualType Ty) const; 7223 bool isFPArgumentType(QualType Ty) const; 7224 QualType GetSingleElementType(QualType Ty) const; 7225 7226 ABIArgInfo classifyReturnType(QualType RetTy) const; 7227 ABIArgInfo classifyArgumentType(QualType ArgTy) const; 7228 7229 void computeInfo(CGFunctionInfo &FI) const override { 7230 if (!getCXXABI().classifyReturnType(FI)) 7231 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7232 for (auto &I : FI.arguments()) 7233 I.info = classifyArgumentType(I.type); 7234 } 7235 7236 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7237 QualType Ty) const override; 7238 7239 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 7240 bool asReturnValue) const override { 7241 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 7242 } 7243 bool isSwiftErrorInRegister() const override { 7244 return false; 7245 } 7246 }; 7247 7248 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo { 7249 public: 7250 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector, bool SoftFloatABI) 7251 : TargetCodeGenInfo( 7252 std::make_unique<SystemZABIInfo>(CGT, HasVector, SoftFloatABI)) {} 7253 }; 7254 7255 } 7256 7257 bool SystemZABIInfo::isPromotableIntegerTypeForABI(QualType Ty) const { 7258 // Treat an enum type as its underlying type. 7259 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7260 Ty = EnumTy->getDecl()->getIntegerType(); 7261 7262 // Promotable integer types are required to be promoted by the ABI. 7263 if (ABIInfo::isPromotableIntegerTypeForABI(Ty)) 7264 return true; 7265 7266 if (const auto *EIT = Ty->getAs<ExtIntType>()) 7267 if (EIT->getNumBits() < 64) 7268 return true; 7269 7270 // 32-bit values must also be promoted. 7271 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 7272 switch (BT->getKind()) { 7273 case BuiltinType::Int: 7274 case BuiltinType::UInt: 7275 return true; 7276 default: 7277 return false; 7278 } 7279 return false; 7280 } 7281 7282 bool SystemZABIInfo::isCompoundType(QualType Ty) const { 7283 return (Ty->isAnyComplexType() || 7284 Ty->isVectorType() || 7285 isAggregateTypeForABI(Ty)); 7286 } 7287 7288 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const { 7289 return (HasVector && 7290 Ty->isVectorType() && 7291 getContext().getTypeSize(Ty) <= 128); 7292 } 7293 7294 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const { 7295 if (IsSoftFloatABI) 7296 return false; 7297 7298 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 7299 switch (BT->getKind()) { 7300 case BuiltinType::Float: 7301 case BuiltinType::Double: 7302 return true; 7303 default: 7304 return false; 7305 } 7306 7307 return false; 7308 } 7309 7310 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const { 7311 const RecordType *RT = Ty->getAs<RecordType>(); 7312 7313 if (RT && RT->isStructureOrClassType()) { 7314 const RecordDecl *RD = RT->getDecl(); 7315 QualType Found; 7316 7317 // If this is a C++ record, check the bases first. 7318 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 7319 for (const auto &I : CXXRD->bases()) { 7320 QualType Base = I.getType(); 7321 7322 // Empty bases don't affect things either way. 7323 if (isEmptyRecord(getContext(), Base, true)) 7324 continue; 7325 7326 if (!Found.isNull()) 7327 return Ty; 7328 Found = GetSingleElementType(Base); 7329 } 7330 7331 // Check the fields. 7332 for (const auto *FD : RD->fields()) { 7333 // For compatibility with GCC, ignore empty bitfields in C++ mode. 7334 // Unlike isSingleElementStruct(), empty structure and array fields 7335 // do count. So do anonymous bitfields that aren't zero-sized. 7336 if (getContext().getLangOpts().CPlusPlus && 7337 FD->isZeroLengthBitField(getContext())) 7338 continue; 7339 // Like isSingleElementStruct(), ignore C++20 empty data members. 7340 if (FD->hasAttr<NoUniqueAddressAttr>() && 7341 isEmptyRecord(getContext(), FD->getType(), true)) 7342 continue; 7343 7344 // Unlike isSingleElementStruct(), arrays do not count. 7345 // Nested structures still do though. 7346 if (!Found.isNull()) 7347 return Ty; 7348 Found = GetSingleElementType(FD->getType()); 7349 } 7350 7351 // Unlike isSingleElementStruct(), trailing padding is allowed. 7352 // An 8-byte aligned struct s { float f; } is passed as a double. 7353 if (!Found.isNull()) 7354 return Found; 7355 } 7356 7357 return Ty; 7358 } 7359 7360 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7361 QualType Ty) const { 7362 // Assume that va_list type is correct; should be pointer to LLVM type: 7363 // struct { 7364 // i64 __gpr; 7365 // i64 __fpr; 7366 // i8 *__overflow_arg_area; 7367 // i8 *__reg_save_area; 7368 // }; 7369 7370 // Every non-vector argument occupies 8 bytes and is passed by preference 7371 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are 7372 // always passed on the stack. 7373 Ty = getContext().getCanonicalType(Ty); 7374 auto TyInfo = getContext().getTypeInfoInChars(Ty); 7375 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty); 7376 llvm::Type *DirectTy = ArgTy; 7377 ABIArgInfo AI = classifyArgumentType(Ty); 7378 bool IsIndirect = AI.isIndirect(); 7379 bool InFPRs = false; 7380 bool IsVector = false; 7381 CharUnits UnpaddedSize; 7382 CharUnits DirectAlign; 7383 if (IsIndirect) { 7384 DirectTy = llvm::PointerType::getUnqual(DirectTy); 7385 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8); 7386 } else { 7387 if (AI.getCoerceToType()) 7388 ArgTy = AI.getCoerceToType(); 7389 InFPRs = (!IsSoftFloatABI && (ArgTy->isFloatTy() || ArgTy->isDoubleTy())); 7390 IsVector = ArgTy->isVectorTy(); 7391 UnpaddedSize = TyInfo.Width; 7392 DirectAlign = TyInfo.Align; 7393 } 7394 CharUnits PaddedSize = CharUnits::fromQuantity(8); 7395 if (IsVector && UnpaddedSize > PaddedSize) 7396 PaddedSize = CharUnits::fromQuantity(16); 7397 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size."); 7398 7399 CharUnits Padding = (PaddedSize - UnpaddedSize); 7400 7401 llvm::Type *IndexTy = CGF.Int64Ty; 7402 llvm::Value *PaddedSizeV = 7403 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity()); 7404 7405 if (IsVector) { 7406 // Work out the address of a vector argument on the stack. 7407 // Vector arguments are always passed in the high bits of a 7408 // single (8 byte) or double (16 byte) stack slot. 7409 Address OverflowArgAreaPtr = 7410 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 7411 Address OverflowArgArea = 7412 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 7413 TyInfo.Align); 7414 Address MemAddr = 7415 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr"); 7416 7417 // Update overflow_arg_area_ptr pointer 7418 llvm::Value *NewOverflowArgArea = 7419 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV, 7420 "overflow_arg_area"); 7421 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 7422 7423 return MemAddr; 7424 } 7425 7426 assert(PaddedSize.getQuantity() == 8); 7427 7428 unsigned MaxRegs, RegCountField, RegSaveIndex; 7429 CharUnits RegPadding; 7430 if (InFPRs) { 7431 MaxRegs = 4; // Maximum of 4 FPR arguments 7432 RegCountField = 1; // __fpr 7433 RegSaveIndex = 16; // save offset for f0 7434 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR 7435 } else { 7436 MaxRegs = 5; // Maximum of 5 GPR arguments 7437 RegCountField = 0; // __gpr 7438 RegSaveIndex = 2; // save offset for r2 7439 RegPadding = Padding; // values are passed in the low bits of a GPR 7440 } 7441 7442 Address RegCountPtr = 7443 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr"); 7444 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count"); 7445 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs); 7446 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV, 7447 "fits_in_regs"); 7448 7449 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 7450 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 7451 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 7452 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 7453 7454 // Emit code to load the value if it was passed in registers. 7455 CGF.EmitBlock(InRegBlock); 7456 7457 // Work out the address of an argument register. 7458 llvm::Value *ScaledRegCount = 7459 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count"); 7460 llvm::Value *RegBase = 7461 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity() 7462 + RegPadding.getQuantity()); 7463 llvm::Value *RegOffset = 7464 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset"); 7465 Address RegSaveAreaPtr = 7466 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr"); 7467 llvm::Value *RegSaveArea = 7468 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area"); 7469 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset, 7470 "raw_reg_addr"), 7471 PaddedSize); 7472 Address RegAddr = 7473 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr"); 7474 7475 // Update the register count 7476 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1); 7477 llvm::Value *NewRegCount = 7478 CGF.Builder.CreateAdd(RegCount, One, "reg_count"); 7479 CGF.Builder.CreateStore(NewRegCount, RegCountPtr); 7480 CGF.EmitBranch(ContBlock); 7481 7482 // Emit code to load the value if it was passed in memory. 7483 CGF.EmitBlock(InMemBlock); 7484 7485 // Work out the address of a stack argument. 7486 Address OverflowArgAreaPtr = 7487 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 7488 Address OverflowArgArea = 7489 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 7490 PaddedSize); 7491 Address RawMemAddr = 7492 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr"); 7493 Address MemAddr = 7494 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr"); 7495 7496 // Update overflow_arg_area_ptr pointer 7497 llvm::Value *NewOverflowArgArea = 7498 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV, 7499 "overflow_arg_area"); 7500 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 7501 CGF.EmitBranch(ContBlock); 7502 7503 // Return the appropriate result. 7504 CGF.EmitBlock(ContBlock); 7505 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 7506 MemAddr, InMemBlock, "va_arg.addr"); 7507 7508 if (IsIndirect) 7509 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"), 7510 TyInfo.Align); 7511 7512 return ResAddr; 7513 } 7514 7515 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const { 7516 if (RetTy->isVoidType()) 7517 return ABIArgInfo::getIgnore(); 7518 if (isVectorArgumentType(RetTy)) 7519 return ABIArgInfo::getDirect(); 7520 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64) 7521 return getNaturalAlignIndirect(RetTy); 7522 return (isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 7523 : ABIArgInfo::getDirect()); 7524 } 7525 7526 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const { 7527 // Handle the generic C++ ABI. 7528 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 7529 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7530 7531 // Integers and enums are extended to full register width. 7532 if (isPromotableIntegerTypeForABI(Ty)) 7533 return ABIArgInfo::getExtend(Ty); 7534 7535 // Handle vector types and vector-like structure types. Note that 7536 // as opposed to float-like structure types, we do not allow any 7537 // padding for vector-like structures, so verify the sizes match. 7538 uint64_t Size = getContext().getTypeSize(Ty); 7539 QualType SingleElementTy = GetSingleElementType(Ty); 7540 if (isVectorArgumentType(SingleElementTy) && 7541 getContext().getTypeSize(SingleElementTy) == Size) 7542 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy)); 7543 7544 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly. 7545 if (Size != 8 && Size != 16 && Size != 32 && Size != 64) 7546 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7547 7548 // Handle small structures. 7549 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7550 // Structures with flexible arrays have variable length, so really 7551 // fail the size test above. 7552 const RecordDecl *RD = RT->getDecl(); 7553 if (RD->hasFlexibleArrayMember()) 7554 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7555 7556 // The structure is passed as an unextended integer, a float, or a double. 7557 llvm::Type *PassTy; 7558 if (isFPArgumentType(SingleElementTy)) { 7559 assert(Size == 32 || Size == 64); 7560 if (Size == 32) 7561 PassTy = llvm::Type::getFloatTy(getVMContext()); 7562 else 7563 PassTy = llvm::Type::getDoubleTy(getVMContext()); 7564 } else 7565 PassTy = llvm::IntegerType::get(getVMContext(), Size); 7566 return ABIArgInfo::getDirect(PassTy); 7567 } 7568 7569 // Non-structure compounds are passed indirectly. 7570 if (isCompoundType(Ty)) 7571 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 7572 7573 return ABIArgInfo::getDirect(nullptr); 7574 } 7575 7576 //===----------------------------------------------------------------------===// 7577 // MSP430 ABI Implementation 7578 //===----------------------------------------------------------------------===// 7579 7580 namespace { 7581 7582 class MSP430ABIInfo : public DefaultABIInfo { 7583 static ABIArgInfo complexArgInfo() { 7584 ABIArgInfo Info = ABIArgInfo::getDirect(); 7585 Info.setCanBeFlattened(false); 7586 return Info; 7587 } 7588 7589 public: 7590 MSP430ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 7591 7592 ABIArgInfo classifyReturnType(QualType RetTy) const { 7593 if (RetTy->isAnyComplexType()) 7594 return complexArgInfo(); 7595 7596 return DefaultABIInfo::classifyReturnType(RetTy); 7597 } 7598 7599 ABIArgInfo classifyArgumentType(QualType RetTy) const { 7600 if (RetTy->isAnyComplexType()) 7601 return complexArgInfo(); 7602 7603 return DefaultABIInfo::classifyArgumentType(RetTy); 7604 } 7605 7606 // Just copy the original implementations because 7607 // DefaultABIInfo::classify{Return,Argument}Type() are not virtual 7608 void computeInfo(CGFunctionInfo &FI) const override { 7609 if (!getCXXABI().classifyReturnType(FI)) 7610 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7611 for (auto &I : FI.arguments()) 7612 I.info = classifyArgumentType(I.type); 7613 } 7614 7615 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7616 QualType Ty) const override { 7617 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 7618 } 7619 }; 7620 7621 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { 7622 public: 7623 MSP430TargetCodeGenInfo(CodeGenTypes &CGT) 7624 : TargetCodeGenInfo(std::make_unique<MSP430ABIInfo>(CGT)) {} 7625 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7626 CodeGen::CodeGenModule &M) const override; 7627 }; 7628 7629 } 7630 7631 void MSP430TargetCodeGenInfo::setTargetAttributes( 7632 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7633 if (GV->isDeclaration()) 7634 return; 7635 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 7636 const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>(); 7637 if (!InterruptAttr) 7638 return; 7639 7640 // Handle 'interrupt' attribute: 7641 llvm::Function *F = cast<llvm::Function>(GV); 7642 7643 // Step 1: Set ISR calling convention. 7644 F->setCallingConv(llvm::CallingConv::MSP430_INTR); 7645 7646 // Step 2: Add attributes goodness. 7647 F->addFnAttr(llvm::Attribute::NoInline); 7648 F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber())); 7649 } 7650 } 7651 7652 //===----------------------------------------------------------------------===// 7653 // MIPS ABI Implementation. This works for both little-endian and 7654 // big-endian variants. 7655 //===----------------------------------------------------------------------===// 7656 7657 namespace { 7658 class MipsABIInfo : public ABIInfo { 7659 bool IsO32; 7660 unsigned MinABIStackAlignInBytes, StackAlignInBytes; 7661 void CoerceToIntArgs(uint64_t TySize, 7662 SmallVectorImpl<llvm::Type *> &ArgList) const; 7663 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const; 7664 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; 7665 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; 7666 public: 7667 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : 7668 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8), 7669 StackAlignInBytes(IsO32 ? 8 : 16) {} 7670 7671 ABIArgInfo classifyReturnType(QualType RetTy) const; 7672 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; 7673 void computeInfo(CGFunctionInfo &FI) const override; 7674 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7675 QualType Ty) const override; 7676 ABIArgInfo extendType(QualType Ty) const; 7677 }; 7678 7679 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { 7680 unsigned SizeOfUnwindException; 7681 public: 7682 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) 7683 : TargetCodeGenInfo(std::make_unique<MipsABIInfo>(CGT, IsO32)), 7684 SizeOfUnwindException(IsO32 ? 24 : 32) {} 7685 7686 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 7687 return 29; 7688 } 7689 7690 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7691 CodeGen::CodeGenModule &CGM) const override { 7692 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7693 if (!FD) return; 7694 llvm::Function *Fn = cast<llvm::Function>(GV); 7695 7696 if (FD->hasAttr<MipsLongCallAttr>()) 7697 Fn->addFnAttr("long-call"); 7698 else if (FD->hasAttr<MipsShortCallAttr>()) 7699 Fn->addFnAttr("short-call"); 7700 7701 // Other attributes do not have a meaning for declarations. 7702 if (GV->isDeclaration()) 7703 return; 7704 7705 if (FD->hasAttr<Mips16Attr>()) { 7706 Fn->addFnAttr("mips16"); 7707 } 7708 else if (FD->hasAttr<NoMips16Attr>()) { 7709 Fn->addFnAttr("nomips16"); 7710 } 7711 7712 if (FD->hasAttr<MicroMipsAttr>()) 7713 Fn->addFnAttr("micromips"); 7714 else if (FD->hasAttr<NoMicroMipsAttr>()) 7715 Fn->addFnAttr("nomicromips"); 7716 7717 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>(); 7718 if (!Attr) 7719 return; 7720 7721 const char *Kind; 7722 switch (Attr->getInterrupt()) { 7723 case MipsInterruptAttr::eic: Kind = "eic"; break; 7724 case MipsInterruptAttr::sw0: Kind = "sw0"; break; 7725 case MipsInterruptAttr::sw1: Kind = "sw1"; break; 7726 case MipsInterruptAttr::hw0: Kind = "hw0"; break; 7727 case MipsInterruptAttr::hw1: Kind = "hw1"; break; 7728 case MipsInterruptAttr::hw2: Kind = "hw2"; break; 7729 case MipsInterruptAttr::hw3: Kind = "hw3"; break; 7730 case MipsInterruptAttr::hw4: Kind = "hw4"; break; 7731 case MipsInterruptAttr::hw5: Kind = "hw5"; break; 7732 } 7733 7734 Fn->addFnAttr("interrupt", Kind); 7735 7736 } 7737 7738 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 7739 llvm::Value *Address) const override; 7740 7741 unsigned getSizeOfUnwindException() const override { 7742 return SizeOfUnwindException; 7743 } 7744 }; 7745 } 7746 7747 void MipsABIInfo::CoerceToIntArgs( 7748 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const { 7749 llvm::IntegerType *IntTy = 7750 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 7751 7752 // Add (TySize / MinABIStackAlignInBytes) args of IntTy. 7753 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N) 7754 ArgList.push_back(IntTy); 7755 7756 // If necessary, add one more integer type to ArgList. 7757 unsigned R = TySize % (MinABIStackAlignInBytes * 8); 7758 7759 if (R) 7760 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); 7761 } 7762 7763 // In N32/64, an aligned double precision floating point field is passed in 7764 // a register. 7765 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const { 7766 SmallVector<llvm::Type*, 8> ArgList, IntArgList; 7767 7768 if (IsO32) { 7769 CoerceToIntArgs(TySize, ArgList); 7770 return llvm::StructType::get(getVMContext(), ArgList); 7771 } 7772 7773 if (Ty->isComplexType()) 7774 return CGT.ConvertType(Ty); 7775 7776 const RecordType *RT = Ty->getAs<RecordType>(); 7777 7778 // Unions/vectors are passed in integer registers. 7779 if (!RT || !RT->isStructureOrClassType()) { 7780 CoerceToIntArgs(TySize, ArgList); 7781 return llvm::StructType::get(getVMContext(), ArgList); 7782 } 7783 7784 const RecordDecl *RD = RT->getDecl(); 7785 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7786 assert(!(TySize % 8) && "Size of structure must be multiple of 8."); 7787 7788 uint64_t LastOffset = 0; 7789 unsigned idx = 0; 7790 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); 7791 7792 // Iterate over fields in the struct/class and check if there are any aligned 7793 // double fields. 7794 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 7795 i != e; ++i, ++idx) { 7796 const QualType Ty = i->getType(); 7797 const BuiltinType *BT = Ty->getAs<BuiltinType>(); 7798 7799 if (!BT || BT->getKind() != BuiltinType::Double) 7800 continue; 7801 7802 uint64_t Offset = Layout.getFieldOffset(idx); 7803 if (Offset % 64) // Ignore doubles that are not aligned. 7804 continue; 7805 7806 // Add ((Offset - LastOffset) / 64) args of type i64. 7807 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) 7808 ArgList.push_back(I64); 7809 7810 // Add double type. 7811 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); 7812 LastOffset = Offset + 64; 7813 } 7814 7815 CoerceToIntArgs(TySize - LastOffset, IntArgList); 7816 ArgList.append(IntArgList.begin(), IntArgList.end()); 7817 7818 return llvm::StructType::get(getVMContext(), ArgList); 7819 } 7820 7821 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset, 7822 uint64_t Offset) const { 7823 if (OrigOffset + MinABIStackAlignInBytes > Offset) 7824 return nullptr; 7825 7826 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8); 7827 } 7828 7829 ABIArgInfo 7830 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { 7831 Ty = useFirstFieldIfTransparentUnion(Ty); 7832 7833 uint64_t OrigOffset = Offset; 7834 uint64_t TySize = getContext().getTypeSize(Ty); 7835 uint64_t Align = getContext().getTypeAlign(Ty) / 8; 7836 7837 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes), 7838 (uint64_t)StackAlignInBytes); 7839 unsigned CurrOffset = llvm::alignTo(Offset, Align); 7840 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8; 7841 7842 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) { 7843 // Ignore empty aggregates. 7844 if (TySize == 0) 7845 return ABIArgInfo::getIgnore(); 7846 7847 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 7848 Offset = OrigOffset + MinABIStackAlignInBytes; 7849 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7850 } 7851 7852 // If we have reached here, aggregates are passed directly by coercing to 7853 // another structure type. Padding is inserted if the offset of the 7854 // aggregate is unaligned. 7855 ABIArgInfo ArgInfo = 7856 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0, 7857 getPaddingType(OrigOffset, CurrOffset)); 7858 ArgInfo.setInReg(true); 7859 return ArgInfo; 7860 } 7861 7862 // Treat an enum type as its underlying type. 7863 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7864 Ty = EnumTy->getDecl()->getIntegerType(); 7865 7866 // Make sure we pass indirectly things that are too large. 7867 if (const auto *EIT = Ty->getAs<ExtIntType>()) 7868 if (EIT->getNumBits() > 128 || 7869 (EIT->getNumBits() > 64 && 7870 !getContext().getTargetInfo().hasInt128Type())) 7871 return getNaturalAlignIndirect(Ty); 7872 7873 // All integral types are promoted to the GPR width. 7874 if (Ty->isIntegralOrEnumerationType()) 7875 return extendType(Ty); 7876 7877 return ABIArgInfo::getDirect( 7878 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset)); 7879 } 7880 7881 llvm::Type* 7882 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { 7883 const RecordType *RT = RetTy->getAs<RecordType>(); 7884 SmallVector<llvm::Type*, 8> RTList; 7885 7886 if (RT && RT->isStructureOrClassType()) { 7887 const RecordDecl *RD = RT->getDecl(); 7888 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7889 unsigned FieldCnt = Layout.getFieldCount(); 7890 7891 // N32/64 returns struct/classes in floating point registers if the 7892 // following conditions are met: 7893 // 1. The size of the struct/class is no larger than 128-bit. 7894 // 2. The struct/class has one or two fields all of which are floating 7895 // point types. 7896 // 3. The offset of the first field is zero (this follows what gcc does). 7897 // 7898 // Any other composite results are returned in integer registers. 7899 // 7900 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { 7901 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); 7902 for (; b != e; ++b) { 7903 const BuiltinType *BT = b->getType()->getAs<BuiltinType>(); 7904 7905 if (!BT || !BT->isFloatingPoint()) 7906 break; 7907 7908 RTList.push_back(CGT.ConvertType(b->getType())); 7909 } 7910 7911 if (b == e) 7912 return llvm::StructType::get(getVMContext(), RTList, 7913 RD->hasAttr<PackedAttr>()); 7914 7915 RTList.clear(); 7916 } 7917 } 7918 7919 CoerceToIntArgs(Size, RTList); 7920 return llvm::StructType::get(getVMContext(), RTList); 7921 } 7922 7923 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { 7924 uint64_t Size = getContext().getTypeSize(RetTy); 7925 7926 if (RetTy->isVoidType()) 7927 return ABIArgInfo::getIgnore(); 7928 7929 // O32 doesn't treat zero-sized structs differently from other structs. 7930 // However, N32/N64 ignores zero sized return values. 7931 if (!IsO32 && Size == 0) 7932 return ABIArgInfo::getIgnore(); 7933 7934 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) { 7935 if (Size <= 128) { 7936 if (RetTy->isAnyComplexType()) 7937 return ABIArgInfo::getDirect(); 7938 7939 // O32 returns integer vectors in registers and N32/N64 returns all small 7940 // aggregates in registers. 7941 if (!IsO32 || 7942 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) { 7943 ABIArgInfo ArgInfo = 7944 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 7945 ArgInfo.setInReg(true); 7946 return ArgInfo; 7947 } 7948 } 7949 7950 return getNaturalAlignIndirect(RetTy); 7951 } 7952 7953 // Treat an enum type as its underlying type. 7954 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7955 RetTy = EnumTy->getDecl()->getIntegerType(); 7956 7957 // Make sure we pass indirectly things that are too large. 7958 if (const auto *EIT = RetTy->getAs<ExtIntType>()) 7959 if (EIT->getNumBits() > 128 || 7960 (EIT->getNumBits() > 64 && 7961 !getContext().getTargetInfo().hasInt128Type())) 7962 return getNaturalAlignIndirect(RetTy); 7963 7964 if (isPromotableIntegerTypeForABI(RetTy)) 7965 return ABIArgInfo::getExtend(RetTy); 7966 7967 if ((RetTy->isUnsignedIntegerOrEnumerationType() || 7968 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32) 7969 return ABIArgInfo::getSignExtend(RetTy); 7970 7971 return ABIArgInfo::getDirect(); 7972 } 7973 7974 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { 7975 ABIArgInfo &RetInfo = FI.getReturnInfo(); 7976 if (!getCXXABI().classifyReturnType(FI)) 7977 RetInfo = classifyReturnType(FI.getReturnType()); 7978 7979 // Check if a pointer to an aggregate is passed as a hidden argument. 7980 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0; 7981 7982 for (auto &I : FI.arguments()) 7983 I.info = classifyArgumentType(I.type, Offset); 7984 } 7985 7986 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7987 QualType OrigTy) const { 7988 QualType Ty = OrigTy; 7989 7990 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64. 7991 // Pointers are also promoted in the same way but this only matters for N32. 7992 unsigned SlotSizeInBits = IsO32 ? 32 : 64; 7993 unsigned PtrWidth = getTarget().getPointerWidth(0); 7994 bool DidPromote = false; 7995 if ((Ty->isIntegerType() && 7996 getContext().getIntWidth(Ty) < SlotSizeInBits) || 7997 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) { 7998 DidPromote = true; 7999 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits, 8000 Ty->isSignedIntegerType()); 8001 } 8002 8003 auto TyInfo = getContext().getTypeInfoInChars(Ty); 8004 8005 // The alignment of things in the argument area is never larger than 8006 // StackAlignInBytes. 8007 TyInfo.Align = 8008 std::min(TyInfo.Align, CharUnits::fromQuantity(StackAlignInBytes)); 8009 8010 // MinABIStackAlignInBytes is the size of argument slots on the stack. 8011 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes); 8012 8013 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 8014 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true); 8015 8016 8017 // If there was a promotion, "unpromote" into a temporary. 8018 // TODO: can we just use a pointer into a subset of the original slot? 8019 if (DidPromote) { 8020 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp"); 8021 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr); 8022 8023 // Truncate down to the right width. 8024 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType() 8025 : CGF.IntPtrTy); 8026 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy); 8027 if (OrigTy->isPointerType()) 8028 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType()); 8029 8030 CGF.Builder.CreateStore(V, Temp); 8031 Addr = Temp; 8032 } 8033 8034 return Addr; 8035 } 8036 8037 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const { 8038 int TySize = getContext().getTypeSize(Ty); 8039 8040 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended. 8041 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 8042 return ABIArgInfo::getSignExtend(Ty); 8043 8044 return ABIArgInfo::getExtend(Ty); 8045 } 8046 8047 bool 8048 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 8049 llvm::Value *Address) const { 8050 // This information comes from gcc's implementation, which seems to 8051 // as canonical as it gets. 8052 8053 // Everything on MIPS is 4 bytes. Double-precision FP registers 8054 // are aliased to pairs of single-precision FP registers. 8055 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 8056 8057 // 0-31 are the general purpose registers, $0 - $31. 8058 // 32-63 are the floating-point registers, $f0 - $f31. 8059 // 64 and 65 are the multiply/divide registers, $hi and $lo. 8060 // 66 is the (notional, I think) register for signal-handler return. 8061 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); 8062 8063 // 67-74 are the floating-point status registers, $fcc0 - $fcc7. 8064 // They are one bit wide and ignored here. 8065 8066 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. 8067 // (coprocessor 1 is the FP unit) 8068 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. 8069 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. 8070 // 176-181 are the DSP accumulator registers. 8071 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); 8072 return false; 8073 } 8074 8075 //===----------------------------------------------------------------------===// 8076 // AVR ABI Implementation. 8077 //===----------------------------------------------------------------------===// 8078 8079 namespace { 8080 class AVRTargetCodeGenInfo : public TargetCodeGenInfo { 8081 public: 8082 AVRTargetCodeGenInfo(CodeGenTypes &CGT) 8083 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 8084 8085 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8086 CodeGen::CodeGenModule &CGM) const override { 8087 if (GV->isDeclaration()) 8088 return; 8089 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 8090 if (!FD) return; 8091 auto *Fn = cast<llvm::Function>(GV); 8092 8093 if (FD->getAttr<AVRInterruptAttr>()) 8094 Fn->addFnAttr("interrupt"); 8095 8096 if (FD->getAttr<AVRSignalAttr>()) 8097 Fn->addFnAttr("signal"); 8098 } 8099 }; 8100 } 8101 8102 //===----------------------------------------------------------------------===// 8103 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. 8104 // Currently subclassed only to implement custom OpenCL C function attribute 8105 // handling. 8106 //===----------------------------------------------------------------------===// 8107 8108 namespace { 8109 8110 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { 8111 public: 8112 TCETargetCodeGenInfo(CodeGenTypes &CGT) 8113 : DefaultTargetCodeGenInfo(CGT) {} 8114 8115 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8116 CodeGen::CodeGenModule &M) const override; 8117 }; 8118 8119 void TCETargetCodeGenInfo::setTargetAttributes( 8120 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8121 if (GV->isDeclaration()) 8122 return; 8123 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8124 if (!FD) return; 8125 8126 llvm::Function *F = cast<llvm::Function>(GV); 8127 8128 if (M.getLangOpts().OpenCL) { 8129 if (FD->hasAttr<OpenCLKernelAttr>()) { 8130 // OpenCL C Kernel functions are not subject to inlining 8131 F->addFnAttr(llvm::Attribute::NoInline); 8132 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>(); 8133 if (Attr) { 8134 // Convert the reqd_work_group_size() attributes to metadata. 8135 llvm::LLVMContext &Context = F->getContext(); 8136 llvm::NamedMDNode *OpenCLMetadata = 8137 M.getModule().getOrInsertNamedMetadata( 8138 "opencl.kernel_wg_size_info"); 8139 8140 SmallVector<llvm::Metadata *, 5> Operands; 8141 Operands.push_back(llvm::ConstantAsMetadata::get(F)); 8142 8143 Operands.push_back( 8144 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8145 M.Int32Ty, llvm::APInt(32, Attr->getXDim())))); 8146 Operands.push_back( 8147 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8148 M.Int32Ty, llvm::APInt(32, Attr->getYDim())))); 8149 Operands.push_back( 8150 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 8151 M.Int32Ty, llvm::APInt(32, Attr->getZDim())))); 8152 8153 // Add a boolean constant operand for "required" (true) or "hint" 8154 // (false) for implementing the work_group_size_hint attr later. 8155 // Currently always true as the hint is not yet implemented. 8156 Operands.push_back( 8157 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context))); 8158 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); 8159 } 8160 } 8161 } 8162 } 8163 8164 } 8165 8166 //===----------------------------------------------------------------------===// 8167 // Hexagon ABI Implementation 8168 //===----------------------------------------------------------------------===// 8169 8170 namespace { 8171 8172 class HexagonABIInfo : public DefaultABIInfo { 8173 public: 8174 HexagonABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8175 8176 private: 8177 ABIArgInfo classifyReturnType(QualType RetTy) const; 8178 ABIArgInfo classifyArgumentType(QualType RetTy) const; 8179 ABIArgInfo classifyArgumentType(QualType RetTy, unsigned *RegsLeft) const; 8180 8181 void computeInfo(CGFunctionInfo &FI) const override; 8182 8183 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8184 QualType Ty) const override; 8185 Address EmitVAArgFromMemory(CodeGenFunction &CFG, Address VAListAddr, 8186 QualType Ty) const; 8187 Address EmitVAArgForHexagon(CodeGenFunction &CFG, Address VAListAddr, 8188 QualType Ty) const; 8189 Address EmitVAArgForHexagonLinux(CodeGenFunction &CFG, Address VAListAddr, 8190 QualType Ty) const; 8191 }; 8192 8193 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { 8194 public: 8195 HexagonTargetCodeGenInfo(CodeGenTypes &CGT) 8196 : TargetCodeGenInfo(std::make_unique<HexagonABIInfo>(CGT)) {} 8197 8198 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 8199 return 29; 8200 } 8201 8202 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8203 CodeGen::CodeGenModule &GCM) const override { 8204 if (GV->isDeclaration()) 8205 return; 8206 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 8207 if (!FD) 8208 return; 8209 } 8210 }; 8211 8212 } // namespace 8213 8214 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { 8215 unsigned RegsLeft = 6; 8216 if (!getCXXABI().classifyReturnType(FI)) 8217 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8218 for (auto &I : FI.arguments()) 8219 I.info = classifyArgumentType(I.type, &RegsLeft); 8220 } 8221 8222 static bool HexagonAdjustRegsLeft(uint64_t Size, unsigned *RegsLeft) { 8223 assert(Size <= 64 && "Not expecting to pass arguments larger than 64 bits" 8224 " through registers"); 8225 8226 if (*RegsLeft == 0) 8227 return false; 8228 8229 if (Size <= 32) { 8230 (*RegsLeft)--; 8231 return true; 8232 } 8233 8234 if (2 <= (*RegsLeft & (~1U))) { 8235 *RegsLeft = (*RegsLeft & (~1U)) - 2; 8236 return true; 8237 } 8238 8239 // Next available register was r5 but candidate was greater than 32-bits so it 8240 // has to go on the stack. However we still consume r5 8241 if (*RegsLeft == 1) 8242 *RegsLeft = 0; 8243 8244 return false; 8245 } 8246 8247 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty, 8248 unsigned *RegsLeft) const { 8249 if (!isAggregateTypeForABI(Ty)) { 8250 // Treat an enum type as its underlying type. 8251 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 8252 Ty = EnumTy->getDecl()->getIntegerType(); 8253 8254 uint64_t Size = getContext().getTypeSize(Ty); 8255 if (Size <= 64) 8256 HexagonAdjustRegsLeft(Size, RegsLeft); 8257 8258 if (Size > 64 && Ty->isExtIntType()) 8259 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8260 8261 return isPromotableIntegerTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty) 8262 : ABIArgInfo::getDirect(); 8263 } 8264 8265 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 8266 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8267 8268 // Ignore empty records. 8269 if (isEmptyRecord(getContext(), Ty, true)) 8270 return ABIArgInfo::getIgnore(); 8271 8272 uint64_t Size = getContext().getTypeSize(Ty); 8273 unsigned Align = getContext().getTypeAlign(Ty); 8274 8275 if (Size > 64) 8276 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8277 8278 if (HexagonAdjustRegsLeft(Size, RegsLeft)) 8279 Align = Size <= 32 ? 32 : 64; 8280 if (Size <= Align) { 8281 // Pass in the smallest viable integer type. 8282 if (!llvm::isPowerOf2_64(Size)) 8283 Size = llvm::NextPowerOf2(Size); 8284 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 8285 } 8286 return DefaultABIInfo::classifyArgumentType(Ty); 8287 } 8288 8289 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { 8290 if (RetTy->isVoidType()) 8291 return ABIArgInfo::getIgnore(); 8292 8293 const TargetInfo &T = CGT.getTarget(); 8294 uint64_t Size = getContext().getTypeSize(RetTy); 8295 8296 if (RetTy->getAs<VectorType>()) { 8297 // HVX vectors are returned in vector registers or register pairs. 8298 if (T.hasFeature("hvx")) { 8299 assert(T.hasFeature("hvx-length64b") || T.hasFeature("hvx-length128b")); 8300 uint64_t VecSize = T.hasFeature("hvx-length64b") ? 64*8 : 128*8; 8301 if (Size == VecSize || Size == 2*VecSize) 8302 return ABIArgInfo::getDirectInReg(); 8303 } 8304 // Large vector types should be returned via memory. 8305 if (Size > 64) 8306 return getNaturalAlignIndirect(RetTy); 8307 } 8308 8309 if (!isAggregateTypeForABI(RetTy)) { 8310 // Treat an enum type as its underlying type. 8311 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 8312 RetTy = EnumTy->getDecl()->getIntegerType(); 8313 8314 if (Size > 64 && RetTy->isExtIntType()) 8315 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 8316 8317 return isPromotableIntegerTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy) 8318 : ABIArgInfo::getDirect(); 8319 } 8320 8321 if (isEmptyRecord(getContext(), RetTy, true)) 8322 return ABIArgInfo::getIgnore(); 8323 8324 // Aggregates <= 8 bytes are returned in registers, other aggregates 8325 // are returned indirectly. 8326 if (Size <= 64) { 8327 // Return in the smallest viable integer type. 8328 if (!llvm::isPowerOf2_64(Size)) 8329 Size = llvm::NextPowerOf2(Size); 8330 return ABIArgInfo::getDirect(llvm::Type::getIntNTy(getVMContext(), Size)); 8331 } 8332 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true); 8333 } 8334 8335 Address HexagonABIInfo::EmitVAArgFromMemory(CodeGenFunction &CGF, 8336 Address VAListAddr, 8337 QualType Ty) const { 8338 // Load the overflow area pointer. 8339 Address __overflow_area_pointer_p = 8340 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 8341 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 8342 __overflow_area_pointer_p, "__overflow_area_pointer"); 8343 8344 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8; 8345 if (Align > 4) { 8346 // Alignment should be a power of 2. 8347 assert((Align & (Align - 1)) == 0 && "Alignment is not power of 2!"); 8348 8349 // overflow_arg_area = (overflow_arg_area + align - 1) & -align; 8350 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int64Ty, Align - 1); 8351 8352 // Add offset to the current pointer to access the argument. 8353 __overflow_area_pointer = 8354 CGF.Builder.CreateGEP(__overflow_area_pointer, Offset); 8355 llvm::Value *AsInt = 8356 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 8357 8358 // Create a mask which should be "AND"ed 8359 // with (overflow_arg_area + align - 1) 8360 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int32Ty, -(int)Align); 8361 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 8362 CGF.Builder.CreateAnd(AsInt, Mask), __overflow_area_pointer->getType(), 8363 "__overflow_area_pointer.align"); 8364 } 8365 8366 // Get the type of the argument from memory and bitcast 8367 // overflow area pointer to the argument type. 8368 llvm::Type *PTy = CGF.ConvertTypeForMem(Ty); 8369 Address AddrTyped = CGF.Builder.CreateBitCast( 8370 Address(__overflow_area_pointer, CharUnits::fromQuantity(Align)), 8371 llvm::PointerType::getUnqual(PTy)); 8372 8373 // Round up to the minimum stack alignment for varargs which is 4 bytes. 8374 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 8375 8376 __overflow_area_pointer = CGF.Builder.CreateGEP( 8377 __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, Offset), 8378 "__overflow_area_pointer.next"); 8379 CGF.Builder.CreateStore(__overflow_area_pointer, __overflow_area_pointer_p); 8380 8381 return AddrTyped; 8382 } 8383 8384 Address HexagonABIInfo::EmitVAArgForHexagon(CodeGenFunction &CGF, 8385 Address VAListAddr, 8386 QualType Ty) const { 8387 // FIXME: Need to handle alignment 8388 llvm::Type *BP = CGF.Int8PtrTy; 8389 llvm::Type *BPP = CGF.Int8PtrPtrTy; 8390 CGBuilderTy &Builder = CGF.Builder; 8391 Address VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP, "ap"); 8392 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur"); 8393 // Handle address alignment for type alignment > 32 bits 8394 uint64_t TyAlign = CGF.getContext().getTypeAlign(Ty) / 8; 8395 if (TyAlign > 4) { 8396 assert((TyAlign & (TyAlign - 1)) == 0 && "Alignment is not power of 2!"); 8397 llvm::Value *AddrAsInt = Builder.CreatePtrToInt(Addr, CGF.Int32Ty); 8398 AddrAsInt = Builder.CreateAdd(AddrAsInt, Builder.getInt32(TyAlign - 1)); 8399 AddrAsInt = Builder.CreateAnd(AddrAsInt, Builder.getInt32(~(TyAlign - 1))); 8400 Addr = Builder.CreateIntToPtr(AddrAsInt, BP); 8401 } 8402 llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty)); 8403 Address AddrTyped = Builder.CreateBitCast( 8404 Address(Addr, CharUnits::fromQuantity(TyAlign)), PTy); 8405 8406 uint64_t Offset = llvm::alignTo(CGF.getContext().getTypeSize(Ty) / 8, 4); 8407 llvm::Value *NextAddr = Builder.CreateGEP( 8408 Addr, llvm::ConstantInt::get(CGF.Int32Ty, Offset), "ap.next"); 8409 Builder.CreateStore(NextAddr, VAListAddrAsBPP); 8410 8411 return AddrTyped; 8412 } 8413 8414 Address HexagonABIInfo::EmitVAArgForHexagonLinux(CodeGenFunction &CGF, 8415 Address VAListAddr, 8416 QualType Ty) const { 8417 int ArgSize = CGF.getContext().getTypeSize(Ty) / 8; 8418 8419 if (ArgSize > 8) 8420 return EmitVAArgFromMemory(CGF, VAListAddr, Ty); 8421 8422 // Here we have check if the argument is in register area or 8423 // in overflow area. 8424 // If the saved register area pointer + argsize rounded up to alignment > 8425 // saved register area end pointer, argument is in overflow area. 8426 unsigned RegsLeft = 6; 8427 Ty = CGF.getContext().getCanonicalType(Ty); 8428 (void)classifyArgumentType(Ty, &RegsLeft); 8429 8430 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg"); 8431 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 8432 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack"); 8433 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 8434 8435 // Get rounded size of the argument.GCC does not allow vararg of 8436 // size < 4 bytes. We follow the same logic here. 8437 ArgSize = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 8438 int ArgAlign = (CGF.getContext().getTypeSize(Ty) <= 32) ? 4 : 8; 8439 8440 // Argument may be in saved register area 8441 CGF.EmitBlock(MaybeRegBlock); 8442 8443 // Load the current saved register area pointer. 8444 Address __current_saved_reg_area_pointer_p = CGF.Builder.CreateStructGEP( 8445 VAListAddr, 0, "__current_saved_reg_area_pointer_p"); 8446 llvm::Value *__current_saved_reg_area_pointer = CGF.Builder.CreateLoad( 8447 __current_saved_reg_area_pointer_p, "__current_saved_reg_area_pointer"); 8448 8449 // Load the saved register area end pointer. 8450 Address __saved_reg_area_end_pointer_p = CGF.Builder.CreateStructGEP( 8451 VAListAddr, 1, "__saved_reg_area_end_pointer_p"); 8452 llvm::Value *__saved_reg_area_end_pointer = CGF.Builder.CreateLoad( 8453 __saved_reg_area_end_pointer_p, "__saved_reg_area_end_pointer"); 8454 8455 // If the size of argument is > 4 bytes, check if the stack 8456 // location is aligned to 8 bytes 8457 if (ArgAlign > 4) { 8458 8459 llvm::Value *__current_saved_reg_area_pointer_int = 8460 CGF.Builder.CreatePtrToInt(__current_saved_reg_area_pointer, 8461 CGF.Int32Ty); 8462 8463 __current_saved_reg_area_pointer_int = CGF.Builder.CreateAdd( 8464 __current_saved_reg_area_pointer_int, 8465 llvm::ConstantInt::get(CGF.Int32Ty, (ArgAlign - 1)), 8466 "align_current_saved_reg_area_pointer"); 8467 8468 __current_saved_reg_area_pointer_int = 8469 CGF.Builder.CreateAnd(__current_saved_reg_area_pointer_int, 8470 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 8471 "align_current_saved_reg_area_pointer"); 8472 8473 __current_saved_reg_area_pointer = 8474 CGF.Builder.CreateIntToPtr(__current_saved_reg_area_pointer_int, 8475 __current_saved_reg_area_pointer->getType(), 8476 "align_current_saved_reg_area_pointer"); 8477 } 8478 8479 llvm::Value *__new_saved_reg_area_pointer = 8480 CGF.Builder.CreateGEP(__current_saved_reg_area_pointer, 8481 llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 8482 "__new_saved_reg_area_pointer"); 8483 8484 llvm::Value *UsingStack = 0; 8485 UsingStack = CGF.Builder.CreateICmpSGT(__new_saved_reg_area_pointer, 8486 __saved_reg_area_end_pointer); 8487 8488 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, InRegBlock); 8489 8490 // Argument in saved register area 8491 // Implement the block where argument is in register saved area 8492 CGF.EmitBlock(InRegBlock); 8493 8494 llvm::Type *PTy = CGF.ConvertType(Ty); 8495 llvm::Value *__saved_reg_area_p = CGF.Builder.CreateBitCast( 8496 __current_saved_reg_area_pointer, llvm::PointerType::getUnqual(PTy)); 8497 8498 CGF.Builder.CreateStore(__new_saved_reg_area_pointer, 8499 __current_saved_reg_area_pointer_p); 8500 8501 CGF.EmitBranch(ContBlock); 8502 8503 // Argument in overflow area 8504 // Implement the block where the argument is in overflow area. 8505 CGF.EmitBlock(OnStackBlock); 8506 8507 // Load the overflow area pointer 8508 Address __overflow_area_pointer_p = 8509 CGF.Builder.CreateStructGEP(VAListAddr, 2, "__overflow_area_pointer_p"); 8510 llvm::Value *__overflow_area_pointer = CGF.Builder.CreateLoad( 8511 __overflow_area_pointer_p, "__overflow_area_pointer"); 8512 8513 // Align the overflow area pointer according to the alignment of the argument 8514 if (ArgAlign > 4) { 8515 llvm::Value *__overflow_area_pointer_int = 8516 CGF.Builder.CreatePtrToInt(__overflow_area_pointer, CGF.Int32Ty); 8517 8518 __overflow_area_pointer_int = 8519 CGF.Builder.CreateAdd(__overflow_area_pointer_int, 8520 llvm::ConstantInt::get(CGF.Int32Ty, ArgAlign - 1), 8521 "align_overflow_area_pointer"); 8522 8523 __overflow_area_pointer_int = 8524 CGF.Builder.CreateAnd(__overflow_area_pointer_int, 8525 llvm::ConstantInt::get(CGF.Int32Ty, -ArgAlign), 8526 "align_overflow_area_pointer"); 8527 8528 __overflow_area_pointer = CGF.Builder.CreateIntToPtr( 8529 __overflow_area_pointer_int, __overflow_area_pointer->getType(), 8530 "align_overflow_area_pointer"); 8531 } 8532 8533 // Get the pointer for next argument in overflow area and store it 8534 // to overflow area pointer. 8535 llvm::Value *__new_overflow_area_pointer = CGF.Builder.CreateGEP( 8536 __overflow_area_pointer, llvm::ConstantInt::get(CGF.Int32Ty, ArgSize), 8537 "__overflow_area_pointer.next"); 8538 8539 CGF.Builder.CreateStore(__new_overflow_area_pointer, 8540 __overflow_area_pointer_p); 8541 8542 CGF.Builder.CreateStore(__new_overflow_area_pointer, 8543 __current_saved_reg_area_pointer_p); 8544 8545 // Bitcast the overflow area pointer to the type of argument. 8546 llvm::Type *OverflowPTy = CGF.ConvertTypeForMem(Ty); 8547 llvm::Value *__overflow_area_p = CGF.Builder.CreateBitCast( 8548 __overflow_area_pointer, llvm::PointerType::getUnqual(OverflowPTy)); 8549 8550 CGF.EmitBranch(ContBlock); 8551 8552 // Get the correct pointer to load the variable argument 8553 // Implement the ContBlock 8554 CGF.EmitBlock(ContBlock); 8555 8556 llvm::Type *MemPTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 8557 llvm::PHINode *ArgAddr = CGF.Builder.CreatePHI(MemPTy, 2, "vaarg.addr"); 8558 ArgAddr->addIncoming(__saved_reg_area_p, InRegBlock); 8559 ArgAddr->addIncoming(__overflow_area_p, OnStackBlock); 8560 8561 return Address(ArgAddr, CharUnits::fromQuantity(ArgAlign)); 8562 } 8563 8564 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8565 QualType Ty) const { 8566 8567 if (getTarget().getTriple().isMusl()) 8568 return EmitVAArgForHexagonLinux(CGF, VAListAddr, Ty); 8569 8570 return EmitVAArgForHexagon(CGF, VAListAddr, Ty); 8571 } 8572 8573 //===----------------------------------------------------------------------===// 8574 // Lanai ABI Implementation 8575 //===----------------------------------------------------------------------===// 8576 8577 namespace { 8578 class LanaiABIInfo : public DefaultABIInfo { 8579 public: 8580 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8581 8582 bool shouldUseInReg(QualType Ty, CCState &State) const; 8583 8584 void computeInfo(CGFunctionInfo &FI) const override { 8585 CCState State(FI); 8586 // Lanai uses 4 registers to pass arguments unless the function has the 8587 // regparm attribute set. 8588 if (FI.getHasRegParm()) { 8589 State.FreeRegs = FI.getRegParm(); 8590 } else { 8591 State.FreeRegs = 4; 8592 } 8593 8594 if (!getCXXABI().classifyReturnType(FI)) 8595 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8596 for (auto &I : FI.arguments()) 8597 I.info = classifyArgumentType(I.type, State); 8598 } 8599 8600 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 8601 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 8602 }; 8603 } // end anonymous namespace 8604 8605 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const { 8606 unsigned Size = getContext().getTypeSize(Ty); 8607 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U; 8608 8609 if (SizeInRegs == 0) 8610 return false; 8611 8612 if (SizeInRegs > State.FreeRegs) { 8613 State.FreeRegs = 0; 8614 return false; 8615 } 8616 8617 State.FreeRegs -= SizeInRegs; 8618 8619 return true; 8620 } 8621 8622 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal, 8623 CCState &State) const { 8624 if (!ByVal) { 8625 if (State.FreeRegs) { 8626 --State.FreeRegs; // Non-byval indirects just use one pointer. 8627 return getNaturalAlignIndirectInReg(Ty); 8628 } 8629 return getNaturalAlignIndirect(Ty, false); 8630 } 8631 8632 // Compute the byval alignment. 8633 const unsigned MinABIStackAlignInBytes = 4; 8634 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 8635 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 8636 /*Realign=*/TypeAlign > 8637 MinABIStackAlignInBytes); 8638 } 8639 8640 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty, 8641 CCState &State) const { 8642 // Check with the C++ ABI first. 8643 const RecordType *RT = Ty->getAs<RecordType>(); 8644 if (RT) { 8645 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 8646 if (RAA == CGCXXABI::RAA_Indirect) { 8647 return getIndirectResult(Ty, /*ByVal=*/false, State); 8648 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 8649 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 8650 } 8651 } 8652 8653 if (isAggregateTypeForABI(Ty)) { 8654 // Structures with flexible arrays are always indirect. 8655 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 8656 return getIndirectResult(Ty, /*ByVal=*/true, State); 8657 8658 // Ignore empty structs/unions. 8659 if (isEmptyRecord(getContext(), Ty, true)) 8660 return ABIArgInfo::getIgnore(); 8661 8662 llvm::LLVMContext &LLVMContext = getVMContext(); 8663 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 8664 if (SizeInRegs <= State.FreeRegs) { 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 State.FreeRegs -= SizeInRegs; 8669 return ABIArgInfo::getDirectInReg(Result); 8670 } else { 8671 State.FreeRegs = 0; 8672 } 8673 return getIndirectResult(Ty, true, State); 8674 } 8675 8676 // Treat an enum type as its underlying type. 8677 if (const auto *EnumTy = Ty->getAs<EnumType>()) 8678 Ty = EnumTy->getDecl()->getIntegerType(); 8679 8680 bool InReg = shouldUseInReg(Ty, State); 8681 8682 // Don't pass >64 bit integers in registers. 8683 if (const auto *EIT = Ty->getAs<ExtIntType>()) 8684 if (EIT->getNumBits() > 64) 8685 return getIndirectResult(Ty, /*ByVal=*/true, State); 8686 8687 if (isPromotableIntegerTypeForABI(Ty)) { 8688 if (InReg) 8689 return ABIArgInfo::getDirectInReg(); 8690 return ABIArgInfo::getExtend(Ty); 8691 } 8692 if (InReg) 8693 return ABIArgInfo::getDirectInReg(); 8694 return ABIArgInfo::getDirect(); 8695 } 8696 8697 namespace { 8698 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo { 8699 public: 8700 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 8701 : TargetCodeGenInfo(std::make_unique<LanaiABIInfo>(CGT)) {} 8702 }; 8703 } 8704 8705 //===----------------------------------------------------------------------===// 8706 // AMDGPU ABI Implementation 8707 //===----------------------------------------------------------------------===// 8708 8709 namespace { 8710 8711 class AMDGPUABIInfo final : public DefaultABIInfo { 8712 private: 8713 static const unsigned MaxNumRegsForArgsRet = 16; 8714 8715 unsigned numRegsForType(QualType Ty) const; 8716 8717 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 8718 bool isHomogeneousAggregateSmallEnough(const Type *Base, 8719 uint64_t Members) const override; 8720 8721 // Coerce HIP scalar pointer arguments from generic pointers to global ones. 8722 llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS, 8723 unsigned ToAS) const { 8724 // Single value types. 8725 if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS) 8726 return llvm::PointerType::get( 8727 cast<llvm::PointerType>(Ty)->getElementType(), ToAS); 8728 return Ty; 8729 } 8730 8731 public: 8732 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : 8733 DefaultABIInfo(CGT) {} 8734 8735 ABIArgInfo classifyReturnType(QualType RetTy) const; 8736 ABIArgInfo classifyKernelArgumentType(QualType Ty) const; 8737 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const; 8738 8739 void computeInfo(CGFunctionInfo &FI) const override; 8740 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8741 QualType Ty) const override; 8742 }; 8743 8744 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 8745 return true; 8746 } 8747 8748 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough( 8749 const Type *Base, uint64_t Members) const { 8750 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32; 8751 8752 // Homogeneous Aggregates may occupy at most 16 registers. 8753 return Members * NumRegs <= MaxNumRegsForArgsRet; 8754 } 8755 8756 /// Estimate number of registers the type will use when passed in registers. 8757 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const { 8758 unsigned NumRegs = 0; 8759 8760 if (const VectorType *VT = Ty->getAs<VectorType>()) { 8761 // Compute from the number of elements. The reported size is based on the 8762 // in-memory size, which includes the padding 4th element for 3-vectors. 8763 QualType EltTy = VT->getElementType(); 8764 unsigned EltSize = getContext().getTypeSize(EltTy); 8765 8766 // 16-bit element vectors should be passed as packed. 8767 if (EltSize == 16) 8768 return (VT->getNumElements() + 1) / 2; 8769 8770 unsigned EltNumRegs = (EltSize + 31) / 32; 8771 return EltNumRegs * VT->getNumElements(); 8772 } 8773 8774 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8775 const RecordDecl *RD = RT->getDecl(); 8776 assert(!RD->hasFlexibleArrayMember()); 8777 8778 for (const FieldDecl *Field : RD->fields()) { 8779 QualType FieldTy = Field->getType(); 8780 NumRegs += numRegsForType(FieldTy); 8781 } 8782 8783 return NumRegs; 8784 } 8785 8786 return (getContext().getTypeSize(Ty) + 31) / 32; 8787 } 8788 8789 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const { 8790 llvm::CallingConv::ID CC = FI.getCallingConvention(); 8791 8792 if (!getCXXABI().classifyReturnType(FI)) 8793 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8794 8795 unsigned NumRegsLeft = MaxNumRegsForArgsRet; 8796 for (auto &Arg : FI.arguments()) { 8797 if (CC == llvm::CallingConv::AMDGPU_KERNEL) { 8798 Arg.info = classifyKernelArgumentType(Arg.type); 8799 } else { 8800 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft); 8801 } 8802 } 8803 } 8804 8805 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8806 QualType Ty) const { 8807 llvm_unreachable("AMDGPU does not support varargs"); 8808 } 8809 8810 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const { 8811 if (isAggregateTypeForABI(RetTy)) { 8812 // Records with non-trivial destructors/copy-constructors should not be 8813 // returned by value. 8814 if (!getRecordArgABI(RetTy, getCXXABI())) { 8815 // Ignore empty structs/unions. 8816 if (isEmptyRecord(getContext(), RetTy, true)) 8817 return ABIArgInfo::getIgnore(); 8818 8819 // Lower single-element structs to just return a regular value. 8820 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 8821 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 8822 8823 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 8824 const RecordDecl *RD = RT->getDecl(); 8825 if (RD->hasFlexibleArrayMember()) 8826 return DefaultABIInfo::classifyReturnType(RetTy); 8827 } 8828 8829 // Pack aggregates <= 4 bytes into single VGPR or pair. 8830 uint64_t Size = getContext().getTypeSize(RetTy); 8831 if (Size <= 16) 8832 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 8833 8834 if (Size <= 32) 8835 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 8836 8837 if (Size <= 64) { 8838 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 8839 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 8840 } 8841 8842 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet) 8843 return ABIArgInfo::getDirect(); 8844 } 8845 } 8846 8847 // Otherwise just do the default thing. 8848 return DefaultABIInfo::classifyReturnType(RetTy); 8849 } 8850 8851 /// For kernels all parameters are really passed in a special buffer. It doesn't 8852 /// make sense to pass anything byval, so everything must be direct. 8853 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const { 8854 Ty = useFirstFieldIfTransparentUnion(Ty); 8855 8856 // TODO: Can we omit empty structs? 8857 8858 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 8859 Ty = QualType(SeltTy, 0); 8860 8861 llvm::Type *OrigLTy = CGT.ConvertType(Ty); 8862 llvm::Type *LTy = OrigLTy; 8863 if (getContext().getLangOpts().HIP) { 8864 LTy = coerceKernelArgumentType( 8865 OrigLTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default), 8866 /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device)); 8867 } 8868 8869 // FIXME: Should also use this for OpenCL, but it requires addressing the 8870 // problem of kernels being called. 8871 // 8872 // FIXME: This doesn't apply the optimization of coercing pointers in structs 8873 // to global address space when using byref. This would require implementing a 8874 // new kind of coercion of the in-memory type when for indirect arguments. 8875 if (!getContext().getLangOpts().OpenCL && LTy == OrigLTy && 8876 isAggregateTypeForABI(Ty)) { 8877 return ABIArgInfo::getIndirectAliased( 8878 getContext().getTypeAlignInChars(Ty), 8879 getContext().getTargetAddressSpace(LangAS::opencl_constant), 8880 false /*Realign*/, nullptr /*Padding*/); 8881 } 8882 8883 // If we set CanBeFlattened to true, CodeGen will expand the struct to its 8884 // individual elements, which confuses the Clover OpenCL backend; therefore we 8885 // have to set it to false here. Other args of getDirect() are just defaults. 8886 return ABIArgInfo::getDirect(LTy, 0, nullptr, false); 8887 } 8888 8889 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty, 8890 unsigned &NumRegsLeft) const { 8891 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow"); 8892 8893 Ty = useFirstFieldIfTransparentUnion(Ty); 8894 8895 if (isAggregateTypeForABI(Ty)) { 8896 // Records with non-trivial destructors/copy-constructors should not be 8897 // passed by value. 8898 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 8899 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8900 8901 // Ignore empty structs/unions. 8902 if (isEmptyRecord(getContext(), Ty, true)) 8903 return ABIArgInfo::getIgnore(); 8904 8905 // Lower single-element structs to just pass a regular value. TODO: We 8906 // could do reasonable-size multiple-element structs too, using getExpand(), 8907 // though watch out for things like bitfields. 8908 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 8909 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 8910 8911 if (const RecordType *RT = Ty->getAs<RecordType>()) { 8912 const RecordDecl *RD = RT->getDecl(); 8913 if (RD->hasFlexibleArrayMember()) 8914 return DefaultABIInfo::classifyArgumentType(Ty); 8915 } 8916 8917 // Pack aggregates <= 8 bytes into single VGPR or pair. 8918 uint64_t Size = getContext().getTypeSize(Ty); 8919 if (Size <= 64) { 8920 unsigned NumRegs = (Size + 31) / 32; 8921 NumRegsLeft -= std::min(NumRegsLeft, NumRegs); 8922 8923 if (Size <= 16) 8924 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 8925 8926 if (Size <= 32) 8927 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 8928 8929 // XXX: Should this be i64 instead, and should the limit increase? 8930 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 8931 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 8932 } 8933 8934 if (NumRegsLeft > 0) { 8935 unsigned NumRegs = numRegsForType(Ty); 8936 if (NumRegsLeft >= NumRegs) { 8937 NumRegsLeft -= NumRegs; 8938 return ABIArgInfo::getDirect(); 8939 } 8940 } 8941 } 8942 8943 // Otherwise just do the default thing. 8944 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty); 8945 if (!ArgInfo.isIndirect()) { 8946 unsigned NumRegs = numRegsForType(Ty); 8947 NumRegsLeft -= std::min(NumRegs, NumRegsLeft); 8948 } 8949 8950 return ArgInfo; 8951 } 8952 8953 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo { 8954 public: 8955 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT) 8956 : TargetCodeGenInfo(std::make_unique<AMDGPUABIInfo>(CGT)) {} 8957 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 8958 CodeGen::CodeGenModule &M) const override; 8959 unsigned getOpenCLKernelCallingConv() const override; 8960 8961 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM, 8962 llvm::PointerType *T, QualType QT) const override; 8963 8964 LangAS getASTAllocaAddressSpace() const override { 8965 return getLangASFromTargetAS( 8966 getABIInfo().getDataLayout().getAllocaAddrSpace()); 8967 } 8968 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, 8969 const VarDecl *D) const override; 8970 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts, 8971 SyncScope Scope, 8972 llvm::AtomicOrdering Ordering, 8973 llvm::LLVMContext &Ctx) const override; 8974 llvm::Function * 8975 createEnqueuedBlockKernel(CodeGenFunction &CGF, 8976 llvm::Function *BlockInvokeFunc, 8977 llvm::Value *BlockLiteral) const override; 8978 bool shouldEmitStaticExternCAliases() const override; 8979 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override; 8980 }; 8981 } 8982 8983 static bool requiresAMDGPUProtectedVisibility(const Decl *D, 8984 llvm::GlobalValue *GV) { 8985 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility) 8986 return false; 8987 8988 return D->hasAttr<OpenCLKernelAttr>() || 8989 (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) || 8990 (isa<VarDecl>(D) && 8991 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 8992 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinSurfaceType() || 8993 cast<VarDecl>(D)->getType()->isCUDADeviceBuiltinTextureType())); 8994 } 8995 8996 void AMDGPUTargetCodeGenInfo::setTargetAttributes( 8997 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 8998 if (requiresAMDGPUProtectedVisibility(D, GV)) { 8999 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 9000 GV->setDSOLocal(true); 9001 } 9002 9003 if (GV->isDeclaration()) 9004 return; 9005 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 9006 if (!FD) 9007 return; 9008 9009 llvm::Function *F = cast<llvm::Function>(GV); 9010 9011 const auto *ReqdWGS = M.getLangOpts().OpenCL ? 9012 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr; 9013 9014 9015 const bool IsOpenCLKernel = M.getLangOpts().OpenCL && 9016 FD->hasAttr<OpenCLKernelAttr>(); 9017 const bool IsHIPKernel = M.getLangOpts().HIP && 9018 FD->hasAttr<CUDAGlobalAttr>(); 9019 if ((IsOpenCLKernel || IsHIPKernel) && 9020 (M.getTriple().getOS() == llvm::Triple::AMDHSA)) 9021 F->addFnAttr("amdgpu-implicitarg-num-bytes", "56"); 9022 9023 if (IsHIPKernel) 9024 F->addFnAttr("uniform-work-group-size", "true"); 9025 9026 9027 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>(); 9028 if (ReqdWGS || FlatWGS) { 9029 unsigned Min = 0; 9030 unsigned Max = 0; 9031 if (FlatWGS) { 9032 Min = FlatWGS->getMin() 9033 ->EvaluateKnownConstInt(M.getContext()) 9034 .getExtValue(); 9035 Max = FlatWGS->getMax() 9036 ->EvaluateKnownConstInt(M.getContext()) 9037 .getExtValue(); 9038 } 9039 if (ReqdWGS && Min == 0 && Max == 0) 9040 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim(); 9041 9042 if (Min != 0) { 9043 assert(Min <= Max && "Min must be less than or equal Max"); 9044 9045 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max); 9046 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 9047 } else 9048 assert(Max == 0 && "Max must be zero"); 9049 } else if (IsOpenCLKernel || IsHIPKernel) { 9050 // By default, restrict the maximum size to a value specified by 9051 // --gpu-max-threads-per-block=n or its default value. 9052 std::string AttrVal = 9053 std::string("1,") + llvm::utostr(M.getLangOpts().GPUMaxThreadsPerBlock); 9054 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 9055 } 9056 9057 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) { 9058 unsigned Min = 9059 Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue(); 9060 unsigned Max = Attr->getMax() ? Attr->getMax() 9061 ->EvaluateKnownConstInt(M.getContext()) 9062 .getExtValue() 9063 : 0; 9064 9065 if (Min != 0) { 9066 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max"); 9067 9068 std::string AttrVal = llvm::utostr(Min); 9069 if (Max != 0) 9070 AttrVal = AttrVal + "," + llvm::utostr(Max); 9071 F->addFnAttr("amdgpu-waves-per-eu", AttrVal); 9072 } else 9073 assert(Max == 0 && "Max must be zero"); 9074 } 9075 9076 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) { 9077 unsigned NumSGPR = Attr->getNumSGPR(); 9078 9079 if (NumSGPR != 0) 9080 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR)); 9081 } 9082 9083 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) { 9084 uint32_t NumVGPR = Attr->getNumVGPR(); 9085 9086 if (NumVGPR != 0) 9087 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR)); 9088 } 9089 9090 if (M.getContext().getTargetInfo().allowAMDGPUUnsafeFPAtomics()) 9091 F->addFnAttr("amdgpu-unsafe-fp-atomics", "true"); 9092 } 9093 9094 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 9095 return llvm::CallingConv::AMDGPU_KERNEL; 9096 } 9097 9098 // Currently LLVM assumes null pointers always have value 0, 9099 // which results in incorrectly transformed IR. Therefore, instead of 9100 // emitting null pointers in private and local address spaces, a null 9101 // pointer in generic address space is emitted which is casted to a 9102 // pointer in local or private address space. 9103 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer( 9104 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT, 9105 QualType QT) const { 9106 if (CGM.getContext().getTargetNullPointerValue(QT) == 0) 9107 return llvm::ConstantPointerNull::get(PT); 9108 9109 auto &Ctx = CGM.getContext(); 9110 auto NPT = llvm::PointerType::get(PT->getElementType(), 9111 Ctx.getTargetAddressSpace(LangAS::opencl_generic)); 9112 return llvm::ConstantExpr::getAddrSpaceCast( 9113 llvm::ConstantPointerNull::get(NPT), PT); 9114 } 9115 9116 LangAS 9117 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 9118 const VarDecl *D) const { 9119 assert(!CGM.getLangOpts().OpenCL && 9120 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 9121 "Address space agnostic languages only"); 9122 LangAS DefaultGlobalAS = getLangASFromTargetAS( 9123 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global)); 9124 if (!D) 9125 return DefaultGlobalAS; 9126 9127 LangAS AddrSpace = D->getType().getAddressSpace(); 9128 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace)); 9129 if (AddrSpace != LangAS::Default) 9130 return AddrSpace; 9131 9132 if (CGM.isTypeConstant(D->getType(), false)) { 9133 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace()) 9134 return ConstAS.getValue(); 9135 } 9136 return DefaultGlobalAS; 9137 } 9138 9139 llvm::SyncScope::ID 9140 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 9141 SyncScope Scope, 9142 llvm::AtomicOrdering Ordering, 9143 llvm::LLVMContext &Ctx) const { 9144 std::string Name; 9145 switch (Scope) { 9146 case SyncScope::OpenCLWorkGroup: 9147 Name = "workgroup"; 9148 break; 9149 case SyncScope::OpenCLDevice: 9150 Name = "agent"; 9151 break; 9152 case SyncScope::OpenCLAllSVMDevices: 9153 Name = ""; 9154 break; 9155 case SyncScope::OpenCLSubGroup: 9156 Name = "wavefront"; 9157 } 9158 9159 if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) { 9160 if (!Name.empty()) 9161 Name = Twine(Twine(Name) + Twine("-")).str(); 9162 9163 Name = Twine(Twine(Name) + Twine("one-as")).str(); 9164 } 9165 9166 return Ctx.getOrInsertSyncScopeID(Name); 9167 } 9168 9169 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 9170 return false; 9171 } 9172 9173 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention( 9174 const FunctionType *&FT) const { 9175 FT = getABIInfo().getContext().adjustFunctionType( 9176 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel)); 9177 } 9178 9179 //===----------------------------------------------------------------------===// 9180 // SPARC v8 ABI Implementation. 9181 // Based on the SPARC Compliance Definition version 2.4.1. 9182 // 9183 // Ensures that complex values are passed in registers. 9184 // 9185 namespace { 9186 class SparcV8ABIInfo : public DefaultABIInfo { 9187 public: 9188 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 9189 9190 private: 9191 ABIArgInfo classifyReturnType(QualType RetTy) const; 9192 void computeInfo(CGFunctionInfo &FI) const override; 9193 }; 9194 } // end anonymous namespace 9195 9196 9197 ABIArgInfo 9198 SparcV8ABIInfo::classifyReturnType(QualType Ty) const { 9199 if (Ty->isAnyComplexType()) { 9200 return ABIArgInfo::getDirect(); 9201 } 9202 else { 9203 return DefaultABIInfo::classifyReturnType(Ty); 9204 } 9205 } 9206 9207 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const { 9208 9209 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9210 for (auto &Arg : FI.arguments()) 9211 Arg.info = classifyArgumentType(Arg.type); 9212 } 9213 9214 namespace { 9215 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo { 9216 public: 9217 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT) 9218 : TargetCodeGenInfo(std::make_unique<SparcV8ABIInfo>(CGT)) {} 9219 }; 9220 } // end anonymous namespace 9221 9222 //===----------------------------------------------------------------------===// 9223 // SPARC v9 ABI Implementation. 9224 // Based on the SPARC Compliance Definition version 2.4.1. 9225 // 9226 // Function arguments a mapped to a nominal "parameter array" and promoted to 9227 // registers depending on their type. Each argument occupies 8 or 16 bytes in 9228 // the array, structs larger than 16 bytes are passed indirectly. 9229 // 9230 // One case requires special care: 9231 // 9232 // struct mixed { 9233 // int i; 9234 // float f; 9235 // }; 9236 // 9237 // When a struct mixed is passed by value, it only occupies 8 bytes in the 9238 // parameter array, but the int is passed in an integer register, and the float 9239 // is passed in a floating point register. This is represented as two arguments 9240 // with the LLVM IR inreg attribute: 9241 // 9242 // declare void f(i32 inreg %i, float inreg %f) 9243 // 9244 // The code generator will only allocate 4 bytes from the parameter array for 9245 // the inreg arguments. All other arguments are allocated a multiple of 8 9246 // bytes. 9247 // 9248 namespace { 9249 class SparcV9ABIInfo : public ABIInfo { 9250 public: 9251 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 9252 9253 private: 9254 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const; 9255 void computeInfo(CGFunctionInfo &FI) const override; 9256 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9257 QualType Ty) const override; 9258 9259 // Coercion type builder for structs passed in registers. The coercion type 9260 // serves two purposes: 9261 // 9262 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned' 9263 // in registers. 9264 // 2. Expose aligned floating point elements as first-level elements, so the 9265 // code generator knows to pass them in floating point registers. 9266 // 9267 // We also compute the InReg flag which indicates that the struct contains 9268 // aligned 32-bit floats. 9269 // 9270 struct CoerceBuilder { 9271 llvm::LLVMContext &Context; 9272 const llvm::DataLayout &DL; 9273 SmallVector<llvm::Type*, 8> Elems; 9274 uint64_t Size; 9275 bool InReg; 9276 9277 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl) 9278 : Context(c), DL(dl), Size(0), InReg(false) {} 9279 9280 // Pad Elems with integers until Size is ToSize. 9281 void pad(uint64_t ToSize) { 9282 assert(ToSize >= Size && "Cannot remove elements"); 9283 if (ToSize == Size) 9284 return; 9285 9286 // Finish the current 64-bit word. 9287 uint64_t Aligned = llvm::alignTo(Size, 64); 9288 if (Aligned > Size && Aligned <= ToSize) { 9289 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size)); 9290 Size = Aligned; 9291 } 9292 9293 // Add whole 64-bit words. 9294 while (Size + 64 <= ToSize) { 9295 Elems.push_back(llvm::Type::getInt64Ty(Context)); 9296 Size += 64; 9297 } 9298 9299 // Final in-word padding. 9300 if (Size < ToSize) { 9301 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size)); 9302 Size = ToSize; 9303 } 9304 } 9305 9306 // Add a floating point element at Offset. 9307 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) { 9308 // Unaligned floats are treated as integers. 9309 if (Offset % Bits) 9310 return; 9311 // The InReg flag is only required if there are any floats < 64 bits. 9312 if (Bits < 64) 9313 InReg = true; 9314 pad(Offset); 9315 Elems.push_back(Ty); 9316 Size = Offset + Bits; 9317 } 9318 9319 // Add a struct type to the coercion type, starting at Offset (in bits). 9320 void addStruct(uint64_t Offset, llvm::StructType *StrTy) { 9321 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy); 9322 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) { 9323 llvm::Type *ElemTy = StrTy->getElementType(i); 9324 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i); 9325 switch (ElemTy->getTypeID()) { 9326 case llvm::Type::StructTyID: 9327 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy)); 9328 break; 9329 case llvm::Type::FloatTyID: 9330 addFloat(ElemOffset, ElemTy, 32); 9331 break; 9332 case llvm::Type::DoubleTyID: 9333 addFloat(ElemOffset, ElemTy, 64); 9334 break; 9335 case llvm::Type::FP128TyID: 9336 addFloat(ElemOffset, ElemTy, 128); 9337 break; 9338 case llvm::Type::PointerTyID: 9339 if (ElemOffset % 64 == 0) { 9340 pad(ElemOffset); 9341 Elems.push_back(ElemTy); 9342 Size += 64; 9343 } 9344 break; 9345 default: 9346 break; 9347 } 9348 } 9349 } 9350 9351 // Check if Ty is a usable substitute for the coercion type. 9352 bool isUsableType(llvm::StructType *Ty) const { 9353 return llvm::makeArrayRef(Elems) == Ty->elements(); 9354 } 9355 9356 // Get the coercion type as a literal struct type. 9357 llvm::Type *getType() const { 9358 if (Elems.size() == 1) 9359 return Elems.front(); 9360 else 9361 return llvm::StructType::get(Context, Elems); 9362 } 9363 }; 9364 }; 9365 } // end anonymous namespace 9366 9367 ABIArgInfo 9368 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const { 9369 if (Ty->isVoidType()) 9370 return ABIArgInfo::getIgnore(); 9371 9372 uint64_t Size = getContext().getTypeSize(Ty); 9373 9374 // Anything too big to fit in registers is passed with an explicit indirect 9375 // pointer / sret pointer. 9376 if (Size > SizeLimit) 9377 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 9378 9379 // Treat an enum type as its underlying type. 9380 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9381 Ty = EnumTy->getDecl()->getIntegerType(); 9382 9383 // Integer types smaller than a register are extended. 9384 if (Size < 64 && Ty->isIntegerType()) 9385 return ABIArgInfo::getExtend(Ty); 9386 9387 if (const auto *EIT = Ty->getAs<ExtIntType>()) 9388 if (EIT->getNumBits() < 64) 9389 return ABIArgInfo::getExtend(Ty); 9390 9391 // Other non-aggregates go in registers. 9392 if (!isAggregateTypeForABI(Ty)) 9393 return ABIArgInfo::getDirect(); 9394 9395 // If a C++ object has either a non-trivial copy constructor or a non-trivial 9396 // destructor, it is passed with an explicit indirect pointer / sret pointer. 9397 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 9398 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 9399 9400 // This is a small aggregate type that should be passed in registers. 9401 // Build a coercion type from the LLVM struct type. 9402 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty)); 9403 if (!StrTy) 9404 return ABIArgInfo::getDirect(); 9405 9406 CoerceBuilder CB(getVMContext(), getDataLayout()); 9407 CB.addStruct(0, StrTy); 9408 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64)); 9409 9410 // Try to use the original type for coercion. 9411 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType(); 9412 9413 if (CB.InReg) 9414 return ABIArgInfo::getDirectInReg(CoerceTy); 9415 else 9416 return ABIArgInfo::getDirect(CoerceTy); 9417 } 9418 9419 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9420 QualType Ty) const { 9421 ABIArgInfo AI = classifyType(Ty, 16 * 8); 9422 llvm::Type *ArgTy = CGT.ConvertType(Ty); 9423 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 9424 AI.setCoerceToType(ArgTy); 9425 9426 CharUnits SlotSize = CharUnits::fromQuantity(8); 9427 9428 CGBuilderTy &Builder = CGF.Builder; 9429 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 9430 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 9431 9432 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 9433 9434 Address ArgAddr = Address::invalid(); 9435 CharUnits Stride; 9436 switch (AI.getKind()) { 9437 case ABIArgInfo::Expand: 9438 case ABIArgInfo::CoerceAndExpand: 9439 case ABIArgInfo::InAlloca: 9440 llvm_unreachable("Unsupported ABI kind for va_arg"); 9441 9442 case ABIArgInfo::Extend: { 9443 Stride = SlotSize; 9444 CharUnits Offset = SlotSize - TypeInfo.Width; 9445 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend"); 9446 break; 9447 } 9448 9449 case ABIArgInfo::Direct: { 9450 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 9451 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize); 9452 ArgAddr = Addr; 9453 break; 9454 } 9455 9456 case ABIArgInfo::Indirect: 9457 case ABIArgInfo::IndirectAliased: 9458 Stride = SlotSize; 9459 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect"); 9460 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"), 9461 TypeInfo.Align); 9462 break; 9463 9464 case ABIArgInfo::Ignore: 9465 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.Align); 9466 } 9467 9468 // Update VAList. 9469 Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next"); 9470 Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 9471 9472 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr"); 9473 } 9474 9475 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const { 9476 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8); 9477 for (auto &I : FI.arguments()) 9478 I.info = classifyType(I.type, 16 * 8); 9479 } 9480 9481 namespace { 9482 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo { 9483 public: 9484 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT) 9485 : TargetCodeGenInfo(std::make_unique<SparcV9ABIInfo>(CGT)) {} 9486 9487 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 9488 return 14; 9489 } 9490 9491 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 9492 llvm::Value *Address) const override; 9493 }; 9494 } // end anonymous namespace 9495 9496 bool 9497 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 9498 llvm::Value *Address) const { 9499 // This is calculated from the LLVM and GCC tables and verified 9500 // against gcc output. AFAIK all ABIs use the same encoding. 9501 9502 CodeGen::CGBuilderTy &Builder = CGF.Builder; 9503 9504 llvm::IntegerType *i8 = CGF.Int8Ty; 9505 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 9506 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 9507 9508 // 0-31: the 8-byte general-purpose registers 9509 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 9510 9511 // 32-63: f0-31, the 4-byte floating-point registers 9512 AssignToArrayRange(Builder, Address, Four8, 32, 63); 9513 9514 // Y = 64 9515 // PSR = 65 9516 // WIM = 66 9517 // TBR = 67 9518 // PC = 68 9519 // NPC = 69 9520 // FSR = 70 9521 // CSR = 71 9522 AssignToArrayRange(Builder, Address, Eight8, 64, 71); 9523 9524 // 72-87: d0-15, the 8-byte floating-point registers 9525 AssignToArrayRange(Builder, Address, Eight8, 72, 87); 9526 9527 return false; 9528 } 9529 9530 // ARC ABI implementation. 9531 namespace { 9532 9533 class ARCABIInfo : public DefaultABIInfo { 9534 public: 9535 using DefaultABIInfo::DefaultABIInfo; 9536 9537 private: 9538 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9539 QualType Ty) const override; 9540 9541 void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const { 9542 if (!State.FreeRegs) 9543 return; 9544 if (Info.isIndirect() && Info.getInReg()) 9545 State.FreeRegs--; 9546 else if (Info.isDirect() && Info.getInReg()) { 9547 unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32; 9548 if (sz < State.FreeRegs) 9549 State.FreeRegs -= sz; 9550 else 9551 State.FreeRegs = 0; 9552 } 9553 } 9554 9555 void computeInfo(CGFunctionInfo &FI) const override { 9556 CCState State(FI); 9557 // ARC uses 8 registers to pass arguments. 9558 State.FreeRegs = 8; 9559 9560 if (!getCXXABI().classifyReturnType(FI)) 9561 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 9562 updateState(FI.getReturnInfo(), FI.getReturnType(), State); 9563 for (auto &I : FI.arguments()) { 9564 I.info = classifyArgumentType(I.type, State.FreeRegs); 9565 updateState(I.info, I.type, State); 9566 } 9567 } 9568 9569 ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const; 9570 ABIArgInfo getIndirectByValue(QualType Ty) const; 9571 ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const; 9572 ABIArgInfo classifyReturnType(QualType RetTy) const; 9573 }; 9574 9575 class ARCTargetCodeGenInfo : public TargetCodeGenInfo { 9576 public: 9577 ARCTargetCodeGenInfo(CodeGenTypes &CGT) 9578 : TargetCodeGenInfo(std::make_unique<ARCABIInfo>(CGT)) {} 9579 }; 9580 9581 9582 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const { 9583 return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) : 9584 getNaturalAlignIndirect(Ty, false); 9585 } 9586 9587 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const { 9588 // Compute the byval alignment. 9589 const unsigned MinABIStackAlignInBytes = 4; 9590 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 9591 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 9592 TypeAlign > MinABIStackAlignInBytes); 9593 } 9594 9595 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9596 QualType Ty) const { 9597 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 9598 getContext().getTypeInfoInChars(Ty), 9599 CharUnits::fromQuantity(4), true); 9600 } 9601 9602 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty, 9603 uint8_t FreeRegs) const { 9604 // Handle the generic C++ ABI. 9605 const RecordType *RT = Ty->getAs<RecordType>(); 9606 if (RT) { 9607 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 9608 if (RAA == CGCXXABI::RAA_Indirect) 9609 return getIndirectByRef(Ty, FreeRegs > 0); 9610 9611 if (RAA == CGCXXABI::RAA_DirectInMemory) 9612 return getIndirectByValue(Ty); 9613 } 9614 9615 // Treat an enum type as its underlying type. 9616 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9617 Ty = EnumTy->getDecl()->getIntegerType(); 9618 9619 auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32; 9620 9621 if (isAggregateTypeForABI(Ty)) { 9622 // Structures with flexible arrays are always indirect. 9623 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 9624 return getIndirectByValue(Ty); 9625 9626 // Ignore empty structs/unions. 9627 if (isEmptyRecord(getContext(), Ty, true)) 9628 return ABIArgInfo::getIgnore(); 9629 9630 llvm::LLVMContext &LLVMContext = getVMContext(); 9631 9632 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 9633 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 9634 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 9635 9636 return FreeRegs >= SizeInRegs ? 9637 ABIArgInfo::getDirectInReg(Result) : 9638 ABIArgInfo::getDirect(Result, 0, nullptr, false); 9639 } 9640 9641 if (const auto *EIT = Ty->getAs<ExtIntType>()) 9642 if (EIT->getNumBits() > 64) 9643 return getIndirectByValue(Ty); 9644 9645 return isPromotableIntegerTypeForABI(Ty) 9646 ? (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) 9647 : ABIArgInfo::getExtend(Ty)) 9648 : (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() 9649 : ABIArgInfo::getDirect()); 9650 } 9651 9652 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const { 9653 if (RetTy->isAnyComplexType()) 9654 return ABIArgInfo::getDirectInReg(); 9655 9656 // Arguments of size > 4 registers are indirect. 9657 auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32; 9658 if (RetSize > 4) 9659 return getIndirectByRef(RetTy, /*HasFreeRegs*/ true); 9660 9661 return DefaultABIInfo::classifyReturnType(RetTy); 9662 } 9663 9664 } // End anonymous namespace. 9665 9666 //===----------------------------------------------------------------------===// 9667 // XCore ABI Implementation 9668 //===----------------------------------------------------------------------===// 9669 9670 namespace { 9671 9672 /// A SmallStringEnc instance is used to build up the TypeString by passing 9673 /// it by reference between functions that append to it. 9674 typedef llvm::SmallString<128> SmallStringEnc; 9675 9676 /// TypeStringCache caches the meta encodings of Types. 9677 /// 9678 /// The reason for caching TypeStrings is two fold: 9679 /// 1. To cache a type's encoding for later uses; 9680 /// 2. As a means to break recursive member type inclusion. 9681 /// 9682 /// A cache Entry can have a Status of: 9683 /// NonRecursive: The type encoding is not recursive; 9684 /// Recursive: The type encoding is recursive; 9685 /// Incomplete: An incomplete TypeString; 9686 /// IncompleteUsed: An incomplete TypeString that has been used in a 9687 /// Recursive type encoding. 9688 /// 9689 /// A NonRecursive entry will have all of its sub-members expanded as fully 9690 /// as possible. Whilst it may contain types which are recursive, the type 9691 /// itself is not recursive and thus its encoding may be safely used whenever 9692 /// the type is encountered. 9693 /// 9694 /// A Recursive entry will have all of its sub-members expanded as fully as 9695 /// possible. The type itself is recursive and it may contain other types which 9696 /// are recursive. The Recursive encoding must not be used during the expansion 9697 /// of a recursive type's recursive branch. For simplicity the code uses 9698 /// IncompleteCount to reject all usage of Recursive encodings for member types. 9699 /// 9700 /// An Incomplete entry is always a RecordType and only encodes its 9701 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and 9702 /// are placed into the cache during type expansion as a means to identify and 9703 /// handle recursive inclusion of types as sub-members. If there is recursion 9704 /// the entry becomes IncompleteUsed. 9705 /// 9706 /// During the expansion of a RecordType's members: 9707 /// 9708 /// If the cache contains a NonRecursive encoding for the member type, the 9709 /// cached encoding is used; 9710 /// 9711 /// If the cache contains a Recursive encoding for the member type, the 9712 /// cached encoding is 'Swapped' out, as it may be incorrect, and... 9713 /// 9714 /// If the member is a RecordType, an Incomplete encoding is placed into the 9715 /// cache to break potential recursive inclusion of itself as a sub-member; 9716 /// 9717 /// Once a member RecordType has been expanded, its temporary incomplete 9718 /// entry is removed from the cache. If a Recursive encoding was swapped out 9719 /// it is swapped back in; 9720 /// 9721 /// If an incomplete entry is used to expand a sub-member, the incomplete 9722 /// entry is marked as IncompleteUsed. The cache keeps count of how many 9723 /// IncompleteUsed entries it currently contains in IncompleteUsedCount; 9724 /// 9725 /// If a member's encoding is found to be a NonRecursive or Recursive viz: 9726 /// IncompleteUsedCount==0, the member's encoding is added to the cache. 9727 /// Else the member is part of a recursive type and thus the recursion has 9728 /// been exited too soon for the encoding to be correct for the member. 9729 /// 9730 class TypeStringCache { 9731 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed}; 9732 struct Entry { 9733 std::string Str; // The encoded TypeString for the type. 9734 enum Status State; // Information about the encoding in 'Str'. 9735 std::string Swapped; // A temporary place holder for a Recursive encoding 9736 // during the expansion of RecordType's members. 9737 }; 9738 std::map<const IdentifierInfo *, struct Entry> Map; 9739 unsigned IncompleteCount; // Number of Incomplete entries in the Map. 9740 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map. 9741 public: 9742 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {} 9743 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc); 9744 bool removeIncomplete(const IdentifierInfo *ID); 9745 void addIfComplete(const IdentifierInfo *ID, StringRef Str, 9746 bool IsRecursive); 9747 StringRef lookupStr(const IdentifierInfo *ID); 9748 }; 9749 9750 /// TypeString encodings for enum & union fields must be order. 9751 /// FieldEncoding is a helper for this ordering process. 9752 class FieldEncoding { 9753 bool HasName; 9754 std::string Enc; 9755 public: 9756 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {} 9757 StringRef str() { return Enc; } 9758 bool operator<(const FieldEncoding &rhs) const { 9759 if (HasName != rhs.HasName) return HasName; 9760 return Enc < rhs.Enc; 9761 } 9762 }; 9763 9764 class XCoreABIInfo : public DefaultABIInfo { 9765 public: 9766 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 9767 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9768 QualType Ty) const override; 9769 }; 9770 9771 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo { 9772 mutable TypeStringCache TSC; 9773 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV, 9774 const CodeGen::CodeGenModule &M) const; 9775 9776 public: 9777 XCoreTargetCodeGenInfo(CodeGenTypes &CGT) 9778 : TargetCodeGenInfo(std::make_unique<XCoreABIInfo>(CGT)) {} 9779 void emitTargetMetadata(CodeGen::CodeGenModule &CGM, 9780 const llvm::MapVector<GlobalDecl, StringRef> 9781 &MangledDeclNames) const override; 9782 }; 9783 9784 } // End anonymous namespace. 9785 9786 // TODO: this implementation is likely now redundant with the default 9787 // EmitVAArg. 9788 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9789 QualType Ty) const { 9790 CGBuilderTy &Builder = CGF.Builder; 9791 9792 // Get the VAList. 9793 CharUnits SlotSize = CharUnits::fromQuantity(4); 9794 Address AP(Builder.CreateLoad(VAListAddr), SlotSize); 9795 9796 // Handle the argument. 9797 ABIArgInfo AI = classifyArgumentType(Ty); 9798 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty); 9799 llvm::Type *ArgTy = CGT.ConvertType(Ty); 9800 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 9801 AI.setCoerceToType(ArgTy); 9802 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 9803 9804 Address Val = Address::invalid(); 9805 CharUnits ArgSize = CharUnits::Zero(); 9806 switch (AI.getKind()) { 9807 case ABIArgInfo::Expand: 9808 case ABIArgInfo::CoerceAndExpand: 9809 case ABIArgInfo::InAlloca: 9810 llvm_unreachable("Unsupported ABI kind for va_arg"); 9811 case ABIArgInfo::Ignore: 9812 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign); 9813 ArgSize = CharUnits::Zero(); 9814 break; 9815 case ABIArgInfo::Extend: 9816 case ABIArgInfo::Direct: 9817 Val = Builder.CreateBitCast(AP, ArgPtrTy); 9818 ArgSize = CharUnits::fromQuantity( 9819 getDataLayout().getTypeAllocSize(AI.getCoerceToType())); 9820 ArgSize = ArgSize.alignTo(SlotSize); 9821 break; 9822 case ABIArgInfo::Indirect: 9823 case ABIArgInfo::IndirectAliased: 9824 Val = Builder.CreateElementBitCast(AP, ArgPtrTy); 9825 Val = Address(Builder.CreateLoad(Val), TypeAlign); 9826 ArgSize = SlotSize; 9827 break; 9828 } 9829 9830 // Increment the VAList. 9831 if (!ArgSize.isZero()) { 9832 Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize); 9833 Builder.CreateStore(APN.getPointer(), VAListAddr); 9834 } 9835 9836 return Val; 9837 } 9838 9839 /// During the expansion of a RecordType, an incomplete TypeString is placed 9840 /// into the cache as a means to identify and break recursion. 9841 /// If there is a Recursive encoding in the cache, it is swapped out and will 9842 /// be reinserted by removeIncomplete(). 9843 /// All other types of encoding should have been used rather than arriving here. 9844 void TypeStringCache::addIncomplete(const IdentifierInfo *ID, 9845 std::string StubEnc) { 9846 if (!ID) 9847 return; 9848 Entry &E = Map[ID]; 9849 assert( (E.Str.empty() || E.State == Recursive) && 9850 "Incorrectly use of addIncomplete"); 9851 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()"); 9852 E.Swapped.swap(E.Str); // swap out the Recursive 9853 E.Str.swap(StubEnc); 9854 E.State = Incomplete; 9855 ++IncompleteCount; 9856 } 9857 9858 /// Once the RecordType has been expanded, the temporary incomplete TypeString 9859 /// must be removed from the cache. 9860 /// If a Recursive was swapped out by addIncomplete(), it will be replaced. 9861 /// Returns true if the RecordType was defined recursively. 9862 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) { 9863 if (!ID) 9864 return false; 9865 auto I = Map.find(ID); 9866 assert(I != Map.end() && "Entry not present"); 9867 Entry &E = I->second; 9868 assert( (E.State == Incomplete || 9869 E.State == IncompleteUsed) && 9870 "Entry must be an incomplete type"); 9871 bool IsRecursive = false; 9872 if (E.State == IncompleteUsed) { 9873 // We made use of our Incomplete encoding, thus we are recursive. 9874 IsRecursive = true; 9875 --IncompleteUsedCount; 9876 } 9877 if (E.Swapped.empty()) 9878 Map.erase(I); 9879 else { 9880 // Swap the Recursive back. 9881 E.Swapped.swap(E.Str); 9882 E.Swapped.clear(); 9883 E.State = Recursive; 9884 } 9885 --IncompleteCount; 9886 return IsRecursive; 9887 } 9888 9889 /// Add the encoded TypeString to the cache only if it is NonRecursive or 9890 /// Recursive (viz: all sub-members were expanded as fully as possible). 9891 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str, 9892 bool IsRecursive) { 9893 if (!ID || IncompleteUsedCount) 9894 return; // No key or it is is an incomplete sub-type so don't add. 9895 Entry &E = Map[ID]; 9896 if (IsRecursive && !E.Str.empty()) { 9897 assert(E.State==Recursive && E.Str.size() == Str.size() && 9898 "This is not the same Recursive entry"); 9899 // The parent container was not recursive after all, so we could have used 9900 // this Recursive sub-member entry after all, but we assumed the worse when 9901 // we started viz: IncompleteCount!=0. 9902 return; 9903 } 9904 assert(E.Str.empty() && "Entry already present"); 9905 E.Str = Str.str(); 9906 E.State = IsRecursive? Recursive : NonRecursive; 9907 } 9908 9909 /// Return a cached TypeString encoding for the ID. If there isn't one, or we 9910 /// are recursively expanding a type (IncompleteCount != 0) and the cached 9911 /// encoding is Recursive, return an empty StringRef. 9912 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) { 9913 if (!ID) 9914 return StringRef(); // We have no key. 9915 auto I = Map.find(ID); 9916 if (I == Map.end()) 9917 return StringRef(); // We have no encoding. 9918 Entry &E = I->second; 9919 if (E.State == Recursive && IncompleteCount) 9920 return StringRef(); // We don't use Recursive encodings for member types. 9921 9922 if (E.State == Incomplete) { 9923 // The incomplete type is being used to break out of recursion. 9924 E.State = IncompleteUsed; 9925 ++IncompleteUsedCount; 9926 } 9927 return E.Str; 9928 } 9929 9930 /// The XCore ABI includes a type information section that communicates symbol 9931 /// type information to the linker. The linker uses this information to verify 9932 /// safety/correctness of things such as array bound and pointers et al. 9933 /// The ABI only requires C (and XC) language modules to emit TypeStrings. 9934 /// This type information (TypeString) is emitted into meta data for all global 9935 /// symbols: definitions, declarations, functions & variables. 9936 /// 9937 /// The TypeString carries type, qualifier, name, size & value details. 9938 /// Please see 'Tools Development Guide' section 2.16.2 for format details: 9939 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf 9940 /// The output is tested by test/CodeGen/xcore-stringtype.c. 9941 /// 9942 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 9943 const CodeGen::CodeGenModule &CGM, 9944 TypeStringCache &TSC); 9945 9946 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols. 9947 void XCoreTargetCodeGenInfo::emitTargetMD( 9948 const Decl *D, llvm::GlobalValue *GV, 9949 const CodeGen::CodeGenModule &CGM) const { 9950 SmallStringEnc Enc; 9951 if (getTypeString(Enc, D, CGM, TSC)) { 9952 llvm::LLVMContext &Ctx = CGM.getModule().getContext(); 9953 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV), 9954 llvm::MDString::get(Ctx, Enc.str())}; 9955 llvm::NamedMDNode *MD = 9956 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings"); 9957 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 9958 } 9959 } 9960 9961 void XCoreTargetCodeGenInfo::emitTargetMetadata( 9962 CodeGen::CodeGenModule &CGM, 9963 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames) const { 9964 // Warning, new MangledDeclNames may be appended within this loop. 9965 // We rely on MapVector insertions adding new elements to the end 9966 // of the container. 9967 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) { 9968 auto Val = *(MangledDeclNames.begin() + I); 9969 llvm::GlobalValue *GV = CGM.GetGlobalValue(Val.second); 9970 if (GV) { 9971 const Decl *D = Val.first.getDecl()->getMostRecentDecl(); 9972 emitTargetMD(D, GV, CGM); 9973 } 9974 } 9975 } 9976 //===----------------------------------------------------------------------===// 9977 // SPIR ABI Implementation 9978 //===----------------------------------------------------------------------===// 9979 9980 namespace { 9981 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo { 9982 public: 9983 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 9984 : TargetCodeGenInfo(std::make_unique<DefaultABIInfo>(CGT)) {} 9985 unsigned getOpenCLKernelCallingConv() const override; 9986 }; 9987 9988 } // End anonymous namespace. 9989 9990 namespace clang { 9991 namespace CodeGen { 9992 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) { 9993 DefaultABIInfo SPIRABI(CGM.getTypes()); 9994 SPIRABI.computeInfo(FI); 9995 } 9996 } 9997 } 9998 9999 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 10000 return llvm::CallingConv::SPIR_KERNEL; 10001 } 10002 10003 static bool appendType(SmallStringEnc &Enc, QualType QType, 10004 const CodeGen::CodeGenModule &CGM, 10005 TypeStringCache &TSC); 10006 10007 /// Helper function for appendRecordType(). 10008 /// Builds a SmallVector containing the encoded field types in declaration 10009 /// order. 10010 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE, 10011 const RecordDecl *RD, 10012 const CodeGen::CodeGenModule &CGM, 10013 TypeStringCache &TSC) { 10014 for (const auto *Field : RD->fields()) { 10015 SmallStringEnc Enc; 10016 Enc += "m("; 10017 Enc += Field->getName(); 10018 Enc += "){"; 10019 if (Field->isBitField()) { 10020 Enc += "b("; 10021 llvm::raw_svector_ostream OS(Enc); 10022 OS << Field->getBitWidthValue(CGM.getContext()); 10023 Enc += ':'; 10024 } 10025 if (!appendType(Enc, Field->getType(), CGM, TSC)) 10026 return false; 10027 if (Field->isBitField()) 10028 Enc += ')'; 10029 Enc += '}'; 10030 FE.emplace_back(!Field->getName().empty(), Enc); 10031 } 10032 return true; 10033 } 10034 10035 /// Appends structure and union types to Enc and adds encoding to cache. 10036 /// Recursively calls appendType (via extractFieldType) for each field. 10037 /// Union types have their fields ordered according to the ABI. 10038 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT, 10039 const CodeGen::CodeGenModule &CGM, 10040 TypeStringCache &TSC, const IdentifierInfo *ID) { 10041 // Append the cached TypeString if we have one. 10042 StringRef TypeString = TSC.lookupStr(ID); 10043 if (!TypeString.empty()) { 10044 Enc += TypeString; 10045 return true; 10046 } 10047 10048 // Start to emit an incomplete TypeString. 10049 size_t Start = Enc.size(); 10050 Enc += (RT->isUnionType()? 'u' : 's'); 10051 Enc += '('; 10052 if (ID) 10053 Enc += ID->getName(); 10054 Enc += "){"; 10055 10056 // We collect all encoded fields and order as necessary. 10057 bool IsRecursive = false; 10058 const RecordDecl *RD = RT->getDecl()->getDefinition(); 10059 if (RD && !RD->field_empty()) { 10060 // An incomplete TypeString stub is placed in the cache for this RecordType 10061 // so that recursive calls to this RecordType will use it whilst building a 10062 // complete TypeString for this RecordType. 10063 SmallVector<FieldEncoding, 16> FE; 10064 std::string StubEnc(Enc.substr(Start).str()); 10065 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString. 10066 TSC.addIncomplete(ID, std::move(StubEnc)); 10067 if (!extractFieldType(FE, RD, CGM, TSC)) { 10068 (void) TSC.removeIncomplete(ID); 10069 return false; 10070 } 10071 IsRecursive = TSC.removeIncomplete(ID); 10072 // The ABI requires unions to be sorted but not structures. 10073 // See FieldEncoding::operator< for sort algorithm. 10074 if (RT->isUnionType()) 10075 llvm::sort(FE); 10076 // We can now complete the TypeString. 10077 unsigned E = FE.size(); 10078 for (unsigned I = 0; I != E; ++I) { 10079 if (I) 10080 Enc += ','; 10081 Enc += FE[I].str(); 10082 } 10083 } 10084 Enc += '}'; 10085 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive); 10086 return true; 10087 } 10088 10089 /// Appends enum types to Enc and adds the encoding to the cache. 10090 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET, 10091 TypeStringCache &TSC, 10092 const IdentifierInfo *ID) { 10093 // Append the cached TypeString if we have one. 10094 StringRef TypeString = TSC.lookupStr(ID); 10095 if (!TypeString.empty()) { 10096 Enc += TypeString; 10097 return true; 10098 } 10099 10100 size_t Start = Enc.size(); 10101 Enc += "e("; 10102 if (ID) 10103 Enc += ID->getName(); 10104 Enc += "){"; 10105 10106 // We collect all encoded enumerations and order them alphanumerically. 10107 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) { 10108 SmallVector<FieldEncoding, 16> FE; 10109 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E; 10110 ++I) { 10111 SmallStringEnc EnumEnc; 10112 EnumEnc += "m("; 10113 EnumEnc += I->getName(); 10114 EnumEnc += "){"; 10115 I->getInitVal().toString(EnumEnc); 10116 EnumEnc += '}'; 10117 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc)); 10118 } 10119 llvm::sort(FE); 10120 unsigned E = FE.size(); 10121 for (unsigned I = 0; I != E; ++I) { 10122 if (I) 10123 Enc += ','; 10124 Enc += FE[I].str(); 10125 } 10126 } 10127 Enc += '}'; 10128 TSC.addIfComplete(ID, Enc.substr(Start), false); 10129 return true; 10130 } 10131 10132 /// Appends type's qualifier to Enc. 10133 /// This is done prior to appending the type's encoding. 10134 static void appendQualifier(SmallStringEnc &Enc, QualType QT) { 10135 // Qualifiers are emitted in alphabetical order. 10136 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"}; 10137 int Lookup = 0; 10138 if (QT.isConstQualified()) 10139 Lookup += 1<<0; 10140 if (QT.isRestrictQualified()) 10141 Lookup += 1<<1; 10142 if (QT.isVolatileQualified()) 10143 Lookup += 1<<2; 10144 Enc += Table[Lookup]; 10145 } 10146 10147 /// Appends built-in types to Enc. 10148 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) { 10149 const char *EncType; 10150 switch (BT->getKind()) { 10151 case BuiltinType::Void: 10152 EncType = "0"; 10153 break; 10154 case BuiltinType::Bool: 10155 EncType = "b"; 10156 break; 10157 case BuiltinType::Char_U: 10158 EncType = "uc"; 10159 break; 10160 case BuiltinType::UChar: 10161 EncType = "uc"; 10162 break; 10163 case BuiltinType::SChar: 10164 EncType = "sc"; 10165 break; 10166 case BuiltinType::UShort: 10167 EncType = "us"; 10168 break; 10169 case BuiltinType::Short: 10170 EncType = "ss"; 10171 break; 10172 case BuiltinType::UInt: 10173 EncType = "ui"; 10174 break; 10175 case BuiltinType::Int: 10176 EncType = "si"; 10177 break; 10178 case BuiltinType::ULong: 10179 EncType = "ul"; 10180 break; 10181 case BuiltinType::Long: 10182 EncType = "sl"; 10183 break; 10184 case BuiltinType::ULongLong: 10185 EncType = "ull"; 10186 break; 10187 case BuiltinType::LongLong: 10188 EncType = "sll"; 10189 break; 10190 case BuiltinType::Float: 10191 EncType = "ft"; 10192 break; 10193 case BuiltinType::Double: 10194 EncType = "d"; 10195 break; 10196 case BuiltinType::LongDouble: 10197 EncType = "ld"; 10198 break; 10199 default: 10200 return false; 10201 } 10202 Enc += EncType; 10203 return true; 10204 } 10205 10206 /// Appends a pointer encoding to Enc before calling appendType for the pointee. 10207 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT, 10208 const CodeGen::CodeGenModule &CGM, 10209 TypeStringCache &TSC) { 10210 Enc += "p("; 10211 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC)) 10212 return false; 10213 Enc += ')'; 10214 return true; 10215 } 10216 10217 /// Appends array encoding to Enc before calling appendType for the element. 10218 static bool appendArrayType(SmallStringEnc &Enc, QualType QT, 10219 const ArrayType *AT, 10220 const CodeGen::CodeGenModule &CGM, 10221 TypeStringCache &TSC, StringRef NoSizeEnc) { 10222 if (AT->getSizeModifier() != ArrayType::Normal) 10223 return false; 10224 Enc += "a("; 10225 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 10226 CAT->getSize().toStringUnsigned(Enc); 10227 else 10228 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "". 10229 Enc += ':'; 10230 // The Qualifiers should be attached to the type rather than the array. 10231 appendQualifier(Enc, QT); 10232 if (!appendType(Enc, AT->getElementType(), CGM, TSC)) 10233 return false; 10234 Enc += ')'; 10235 return true; 10236 } 10237 10238 /// Appends a function encoding to Enc, calling appendType for the return type 10239 /// and the arguments. 10240 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT, 10241 const CodeGen::CodeGenModule &CGM, 10242 TypeStringCache &TSC) { 10243 Enc += "f{"; 10244 if (!appendType(Enc, FT->getReturnType(), CGM, TSC)) 10245 return false; 10246 Enc += "}("; 10247 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) { 10248 // N.B. we are only interested in the adjusted param types. 10249 auto I = FPT->param_type_begin(); 10250 auto E = FPT->param_type_end(); 10251 if (I != E) { 10252 do { 10253 if (!appendType(Enc, *I, CGM, TSC)) 10254 return false; 10255 ++I; 10256 if (I != E) 10257 Enc += ','; 10258 } while (I != E); 10259 if (FPT->isVariadic()) 10260 Enc += ",va"; 10261 } else { 10262 if (FPT->isVariadic()) 10263 Enc += "va"; 10264 else 10265 Enc += '0'; 10266 } 10267 } 10268 Enc += ')'; 10269 return true; 10270 } 10271 10272 /// Handles the type's qualifier before dispatching a call to handle specific 10273 /// type encodings. 10274 static bool appendType(SmallStringEnc &Enc, QualType QType, 10275 const CodeGen::CodeGenModule &CGM, 10276 TypeStringCache &TSC) { 10277 10278 QualType QT = QType.getCanonicalType(); 10279 10280 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) 10281 // The Qualifiers should be attached to the type rather than the array. 10282 // Thus we don't call appendQualifier() here. 10283 return appendArrayType(Enc, QT, AT, CGM, TSC, ""); 10284 10285 appendQualifier(Enc, QT); 10286 10287 if (const BuiltinType *BT = QT->getAs<BuiltinType>()) 10288 return appendBuiltinType(Enc, BT); 10289 10290 if (const PointerType *PT = QT->getAs<PointerType>()) 10291 return appendPointerType(Enc, PT, CGM, TSC); 10292 10293 if (const EnumType *ET = QT->getAs<EnumType>()) 10294 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier()); 10295 10296 if (const RecordType *RT = QT->getAsStructureType()) 10297 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 10298 10299 if (const RecordType *RT = QT->getAsUnionType()) 10300 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 10301 10302 if (const FunctionType *FT = QT->getAs<FunctionType>()) 10303 return appendFunctionType(Enc, FT, CGM, TSC); 10304 10305 return false; 10306 } 10307 10308 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 10309 const CodeGen::CodeGenModule &CGM, 10310 TypeStringCache &TSC) { 10311 if (!D) 10312 return false; 10313 10314 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10315 if (FD->getLanguageLinkage() != CLanguageLinkage) 10316 return false; 10317 return appendType(Enc, FD->getType(), CGM, TSC); 10318 } 10319 10320 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 10321 if (VD->getLanguageLinkage() != CLanguageLinkage) 10322 return false; 10323 QualType QT = VD->getType().getCanonicalType(); 10324 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) { 10325 // Global ArrayTypes are given a size of '*' if the size is unknown. 10326 // The Qualifiers should be attached to the type rather than the array. 10327 // Thus we don't call appendQualifier() here. 10328 return appendArrayType(Enc, QT, AT, CGM, TSC, "*"); 10329 } 10330 return appendType(Enc, QT, CGM, TSC); 10331 } 10332 return false; 10333 } 10334 10335 //===----------------------------------------------------------------------===// 10336 // RISCV ABI Implementation 10337 //===----------------------------------------------------------------------===// 10338 10339 namespace { 10340 class RISCVABIInfo : public DefaultABIInfo { 10341 private: 10342 // Size of the integer ('x') registers in bits. 10343 unsigned XLen; 10344 // Size of the floating point ('f') registers in bits. Note that the target 10345 // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target 10346 // with soft float ABI has FLen==0). 10347 unsigned FLen; 10348 static const int NumArgGPRs = 8; 10349 static const int NumArgFPRs = 8; 10350 bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 10351 llvm::Type *&Field1Ty, 10352 CharUnits &Field1Off, 10353 llvm::Type *&Field2Ty, 10354 CharUnits &Field2Off) const; 10355 10356 public: 10357 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen) 10358 : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {} 10359 10360 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 10361 // non-virtual, but computeInfo is virtual, so we overload it. 10362 void computeInfo(CGFunctionInfo &FI) const override; 10363 10364 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft, 10365 int &ArgFPRsLeft) const; 10366 ABIArgInfo classifyReturnType(QualType RetTy) const; 10367 10368 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10369 QualType Ty) const override; 10370 10371 ABIArgInfo extendType(QualType Ty) const; 10372 10373 bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 10374 CharUnits &Field1Off, llvm::Type *&Field2Ty, 10375 CharUnits &Field2Off, int &NeededArgGPRs, 10376 int &NeededArgFPRs) const; 10377 ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty, 10378 CharUnits Field1Off, 10379 llvm::Type *Field2Ty, 10380 CharUnits Field2Off) const; 10381 }; 10382 } // end anonymous namespace 10383 10384 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const { 10385 QualType RetTy = FI.getReturnType(); 10386 if (!getCXXABI().classifyReturnType(FI)) 10387 FI.getReturnInfo() = classifyReturnType(RetTy); 10388 10389 // IsRetIndirect is true if classifyArgumentType indicated the value should 10390 // be passed indirect, or if the type size is a scalar greater than 2*XLen 10391 // and not a complex type with elements <= FLen. e.g. fp128 is passed direct 10392 // in LLVM IR, relying on the backend lowering code to rewrite the argument 10393 // list and pass indirectly on RV32. 10394 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect; 10395 if (!IsRetIndirect && RetTy->isScalarType() && 10396 getContext().getTypeSize(RetTy) > (2 * XLen)) { 10397 if (RetTy->isComplexType() && FLen) { 10398 QualType EltTy = RetTy->castAs<ComplexType>()->getElementType(); 10399 IsRetIndirect = getContext().getTypeSize(EltTy) > FLen; 10400 } else { 10401 // This is a normal scalar > 2*XLen, such as fp128 on RV32. 10402 IsRetIndirect = true; 10403 } 10404 } 10405 10406 // We must track the number of GPRs used in order to conform to the RISC-V 10407 // ABI, as integer scalars passed in registers should have signext/zeroext 10408 // when promoted, but are anyext if passed on the stack. As GPR usage is 10409 // different for variadic arguments, we must also track whether we are 10410 // examining a vararg or not. 10411 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs; 10412 int ArgFPRsLeft = FLen ? NumArgFPRs : 0; 10413 int NumFixedArgs = FI.getNumRequiredArgs(); 10414 10415 int ArgNum = 0; 10416 for (auto &ArgInfo : FI.arguments()) { 10417 bool IsFixed = ArgNum < NumFixedArgs; 10418 ArgInfo.info = 10419 classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft); 10420 ArgNum++; 10421 } 10422 } 10423 10424 // Returns true if the struct is a potential candidate for the floating point 10425 // calling convention. If this function returns true, the caller is 10426 // responsible for checking that if there is only a single field then that 10427 // field is a float. 10428 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff, 10429 llvm::Type *&Field1Ty, 10430 CharUnits &Field1Off, 10431 llvm::Type *&Field2Ty, 10432 CharUnits &Field2Off) const { 10433 bool IsInt = Ty->isIntegralOrEnumerationType(); 10434 bool IsFloat = Ty->isRealFloatingType(); 10435 10436 if (IsInt || IsFloat) { 10437 uint64_t Size = getContext().getTypeSize(Ty); 10438 if (IsInt && Size > XLen) 10439 return false; 10440 // Can't be eligible if larger than the FP registers. Half precision isn't 10441 // currently supported on RISC-V and the ABI hasn't been confirmed, so 10442 // default to the integer ABI in that case. 10443 if (IsFloat && (Size > FLen || Size < 32)) 10444 return false; 10445 // Can't be eligible if an integer type was already found (int+int pairs 10446 // are not eligible). 10447 if (IsInt && Field1Ty && Field1Ty->isIntegerTy()) 10448 return false; 10449 if (!Field1Ty) { 10450 Field1Ty = CGT.ConvertType(Ty); 10451 Field1Off = CurOff; 10452 return true; 10453 } 10454 if (!Field2Ty) { 10455 Field2Ty = CGT.ConvertType(Ty); 10456 Field2Off = CurOff; 10457 return true; 10458 } 10459 return false; 10460 } 10461 10462 if (auto CTy = Ty->getAs<ComplexType>()) { 10463 if (Field1Ty) 10464 return false; 10465 QualType EltTy = CTy->getElementType(); 10466 if (getContext().getTypeSize(EltTy) > FLen) 10467 return false; 10468 Field1Ty = CGT.ConvertType(EltTy); 10469 Field1Off = CurOff; 10470 assert(CurOff.isZero() && "Unexpected offset for first field"); 10471 Field2Ty = Field1Ty; 10472 Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy); 10473 return true; 10474 } 10475 10476 if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) { 10477 uint64_t ArraySize = ATy->getSize().getZExtValue(); 10478 QualType EltTy = ATy->getElementType(); 10479 CharUnits EltSize = getContext().getTypeSizeInChars(EltTy); 10480 for (uint64_t i = 0; i < ArraySize; ++i) { 10481 bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty, 10482 Field1Off, Field2Ty, Field2Off); 10483 if (!Ret) 10484 return false; 10485 CurOff += EltSize; 10486 } 10487 return true; 10488 } 10489 10490 if (const auto *RTy = Ty->getAs<RecordType>()) { 10491 // Structures with either a non-trivial destructor or a non-trivial 10492 // copy constructor are not eligible for the FP calling convention. 10493 if (getRecordArgABI(Ty, CGT.getCXXABI())) 10494 return false; 10495 if (isEmptyRecord(getContext(), Ty, true)) 10496 return true; 10497 const RecordDecl *RD = RTy->getDecl(); 10498 // Unions aren't eligible unless they're empty (which is caught above). 10499 if (RD->isUnion()) 10500 return false; 10501 int ZeroWidthBitFieldCount = 0; 10502 for (const FieldDecl *FD : RD->fields()) { 10503 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 10504 uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex()); 10505 QualType QTy = FD->getType(); 10506 if (FD->isBitField()) { 10507 unsigned BitWidth = FD->getBitWidthValue(getContext()); 10508 // Allow a bitfield with a type greater than XLen as long as the 10509 // bitwidth is XLen or less. 10510 if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen) 10511 QTy = getContext().getIntTypeForBitwidth(XLen, false); 10512 if (BitWidth == 0) { 10513 ZeroWidthBitFieldCount++; 10514 continue; 10515 } 10516 } 10517 10518 bool Ret = detectFPCCEligibleStructHelper( 10519 QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits), 10520 Field1Ty, Field1Off, Field2Ty, Field2Off); 10521 if (!Ret) 10522 return false; 10523 10524 // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp 10525 // or int+fp structs, but are ignored for a struct with an fp field and 10526 // any number of zero-width bitfields. 10527 if (Field2Ty && ZeroWidthBitFieldCount > 0) 10528 return false; 10529 } 10530 return Field1Ty != nullptr; 10531 } 10532 10533 return false; 10534 } 10535 10536 // Determine if a struct is eligible for passing according to the floating 10537 // point calling convention (i.e., when flattened it contains a single fp 10538 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and 10539 // NeededArgGPRs are incremented appropriately. 10540 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty, 10541 CharUnits &Field1Off, 10542 llvm::Type *&Field2Ty, 10543 CharUnits &Field2Off, 10544 int &NeededArgGPRs, 10545 int &NeededArgFPRs) const { 10546 Field1Ty = nullptr; 10547 Field2Ty = nullptr; 10548 NeededArgGPRs = 0; 10549 NeededArgFPRs = 0; 10550 bool IsCandidate = detectFPCCEligibleStructHelper( 10551 Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off); 10552 // Not really a candidate if we have a single int but no float. 10553 if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy()) 10554 return false; 10555 if (!IsCandidate) 10556 return false; 10557 if (Field1Ty && Field1Ty->isFloatingPointTy()) 10558 NeededArgFPRs++; 10559 else if (Field1Ty) 10560 NeededArgGPRs++; 10561 if (Field2Ty && Field2Ty->isFloatingPointTy()) 10562 NeededArgFPRs++; 10563 else if (Field2Ty) 10564 NeededArgGPRs++; 10565 return IsCandidate; 10566 } 10567 10568 // Call getCoerceAndExpand for the two-element flattened struct described by 10569 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an 10570 // appropriate coerceToType and unpaddedCoerceToType. 10571 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct( 10572 llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty, 10573 CharUnits Field2Off) const { 10574 SmallVector<llvm::Type *, 3> CoerceElts; 10575 SmallVector<llvm::Type *, 2> UnpaddedCoerceElts; 10576 if (!Field1Off.isZero()) 10577 CoerceElts.push_back(llvm::ArrayType::get( 10578 llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity())); 10579 10580 CoerceElts.push_back(Field1Ty); 10581 UnpaddedCoerceElts.push_back(Field1Ty); 10582 10583 if (!Field2Ty) { 10584 return ABIArgInfo::getCoerceAndExpand( 10585 llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()), 10586 UnpaddedCoerceElts[0]); 10587 } 10588 10589 CharUnits Field2Align = 10590 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty)); 10591 CharUnits Field1Size = 10592 CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty)); 10593 CharUnits Field2OffNoPadNoPack = Field1Size.alignTo(Field2Align); 10594 10595 CharUnits Padding = CharUnits::Zero(); 10596 if (Field2Off > Field2OffNoPadNoPack) 10597 Padding = Field2Off - Field2OffNoPadNoPack; 10598 else if (Field2Off != Field2Align && Field2Off > Field1Size) 10599 Padding = Field2Off - Field1Size; 10600 10601 bool IsPacked = !Field2Off.isMultipleOf(Field2Align); 10602 10603 if (!Padding.isZero()) 10604 CoerceElts.push_back(llvm::ArrayType::get( 10605 llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity())); 10606 10607 CoerceElts.push_back(Field2Ty); 10608 UnpaddedCoerceElts.push_back(Field2Ty); 10609 10610 auto CoerceToType = 10611 llvm::StructType::get(getVMContext(), CoerceElts, IsPacked); 10612 auto UnpaddedCoerceToType = 10613 llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked); 10614 10615 return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType); 10616 } 10617 10618 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed, 10619 int &ArgGPRsLeft, 10620 int &ArgFPRsLeft) const { 10621 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow"); 10622 Ty = useFirstFieldIfTransparentUnion(Ty); 10623 10624 // Structures with either a non-trivial destructor or a non-trivial 10625 // copy constructor are always passed indirectly. 10626 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 10627 if (ArgGPRsLeft) 10628 ArgGPRsLeft -= 1; 10629 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 10630 CGCXXABI::RAA_DirectInMemory); 10631 } 10632 10633 // Ignore empty structs/unions. 10634 if (isEmptyRecord(getContext(), Ty, true)) 10635 return ABIArgInfo::getIgnore(); 10636 10637 uint64_t Size = getContext().getTypeSize(Ty); 10638 10639 // Pass floating point values via FPRs if possible. 10640 if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() && 10641 FLen >= Size && ArgFPRsLeft) { 10642 ArgFPRsLeft--; 10643 return ABIArgInfo::getDirect(); 10644 } 10645 10646 // Complex types for the hard float ABI must be passed direct rather than 10647 // using CoerceAndExpand. 10648 if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) { 10649 QualType EltTy = Ty->castAs<ComplexType>()->getElementType(); 10650 if (getContext().getTypeSize(EltTy) <= FLen) { 10651 ArgFPRsLeft -= 2; 10652 return ABIArgInfo::getDirect(); 10653 } 10654 } 10655 10656 if (IsFixed && FLen && Ty->isStructureOrClassType()) { 10657 llvm::Type *Field1Ty = nullptr; 10658 llvm::Type *Field2Ty = nullptr; 10659 CharUnits Field1Off = CharUnits::Zero(); 10660 CharUnits Field2Off = CharUnits::Zero(); 10661 int NeededArgGPRs; 10662 int NeededArgFPRs; 10663 bool IsCandidate = 10664 detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off, 10665 NeededArgGPRs, NeededArgFPRs); 10666 if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft && 10667 NeededArgFPRs <= ArgFPRsLeft) { 10668 ArgGPRsLeft -= NeededArgGPRs; 10669 ArgFPRsLeft -= NeededArgFPRs; 10670 return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty, 10671 Field2Off); 10672 } 10673 } 10674 10675 uint64_t NeededAlign = getContext().getTypeAlign(Ty); 10676 bool MustUseStack = false; 10677 // Determine the number of GPRs needed to pass the current argument 10678 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned" 10679 // register pairs, so may consume 3 registers. 10680 int NeededArgGPRs = 1; 10681 if (!IsFixed && NeededAlign == 2 * XLen) 10682 NeededArgGPRs = 2 + (ArgGPRsLeft % 2); 10683 else if (Size > XLen && Size <= 2 * XLen) 10684 NeededArgGPRs = 2; 10685 10686 if (NeededArgGPRs > ArgGPRsLeft) { 10687 MustUseStack = true; 10688 NeededArgGPRs = ArgGPRsLeft; 10689 } 10690 10691 ArgGPRsLeft -= NeededArgGPRs; 10692 10693 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) { 10694 // Treat an enum type as its underlying type. 10695 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 10696 Ty = EnumTy->getDecl()->getIntegerType(); 10697 10698 // All integral types are promoted to XLen width, unless passed on the 10699 // stack. 10700 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) { 10701 return extendType(Ty); 10702 } 10703 10704 if (const auto *EIT = Ty->getAs<ExtIntType>()) { 10705 if (EIT->getNumBits() < XLen && !MustUseStack) 10706 return extendType(Ty); 10707 if (EIT->getNumBits() > 128 || 10708 (!getContext().getTargetInfo().hasInt128Type() && 10709 EIT->getNumBits() > 64)) 10710 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 10711 } 10712 10713 return ABIArgInfo::getDirect(); 10714 } 10715 10716 // Aggregates which are <= 2*XLen will be passed in registers if possible, 10717 // so coerce to integers. 10718 if (Size <= 2 * XLen) { 10719 unsigned Alignment = getContext().getTypeAlign(Ty); 10720 10721 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is 10722 // required, and a 2-element XLen array if only XLen alignment is required. 10723 if (Size <= XLen) { 10724 return ABIArgInfo::getDirect( 10725 llvm::IntegerType::get(getVMContext(), XLen)); 10726 } else if (Alignment == 2 * XLen) { 10727 return ABIArgInfo::getDirect( 10728 llvm::IntegerType::get(getVMContext(), 2 * XLen)); 10729 } else { 10730 return ABIArgInfo::getDirect(llvm::ArrayType::get( 10731 llvm::IntegerType::get(getVMContext(), XLen), 2)); 10732 } 10733 } 10734 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 10735 } 10736 10737 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const { 10738 if (RetTy->isVoidType()) 10739 return ABIArgInfo::getIgnore(); 10740 10741 int ArgGPRsLeft = 2; 10742 int ArgFPRsLeft = FLen ? 2 : 0; 10743 10744 // The rules for return and argument types are the same, so defer to 10745 // classifyArgumentType. 10746 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft, 10747 ArgFPRsLeft); 10748 } 10749 10750 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 10751 QualType Ty) const { 10752 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8); 10753 10754 // Empty records are ignored for parameter passing purposes. 10755 if (isEmptyRecord(getContext(), Ty, true)) { 10756 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 10757 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 10758 return Addr; 10759 } 10760 10761 auto TInfo = getContext().getTypeInfoInChars(Ty); 10762 10763 // Arguments bigger than 2*Xlen bytes are passed indirectly. 10764 bool IsIndirect = TInfo.Width > 2 * SlotSize; 10765 10766 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TInfo, 10767 SlotSize, /*AllowHigherAlign=*/true); 10768 } 10769 10770 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const { 10771 int TySize = getContext().getTypeSize(Ty); 10772 // RV64 ABI requires unsigned 32 bit integers to be sign extended. 10773 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 10774 return ABIArgInfo::getSignExtend(Ty); 10775 return ABIArgInfo::getExtend(Ty); 10776 } 10777 10778 namespace { 10779 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo { 10780 public: 10781 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, 10782 unsigned FLen) 10783 : TargetCodeGenInfo(std::make_unique<RISCVABIInfo>(CGT, XLen, FLen)) {} 10784 10785 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 10786 CodeGen::CodeGenModule &CGM) const override { 10787 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 10788 if (!FD) return; 10789 10790 const auto *Attr = FD->getAttr<RISCVInterruptAttr>(); 10791 if (!Attr) 10792 return; 10793 10794 const char *Kind; 10795 switch (Attr->getInterrupt()) { 10796 case RISCVInterruptAttr::user: Kind = "user"; break; 10797 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break; 10798 case RISCVInterruptAttr::machine: Kind = "machine"; break; 10799 } 10800 10801 auto *Fn = cast<llvm::Function>(GV); 10802 10803 Fn->addFnAttr("interrupt", Kind); 10804 } 10805 }; 10806 } // namespace 10807 10808 //===----------------------------------------------------------------------===// 10809 // VE ABI Implementation. 10810 // 10811 namespace { 10812 class VEABIInfo : public DefaultABIInfo { 10813 public: 10814 VEABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 10815 10816 private: 10817 ABIArgInfo classifyReturnType(QualType RetTy) const; 10818 ABIArgInfo classifyArgumentType(QualType RetTy) const; 10819 void computeInfo(CGFunctionInfo &FI) const override; 10820 }; 10821 } // end anonymous namespace 10822 10823 ABIArgInfo VEABIInfo::classifyReturnType(QualType Ty) const { 10824 if (Ty->isAnyComplexType()) 10825 return ABIArgInfo::getDirect(); 10826 uint64_t Size = getContext().getTypeSize(Ty); 10827 if (Size < 64 && Ty->isIntegerType()) 10828 return ABIArgInfo::getExtend(Ty); 10829 return DefaultABIInfo::classifyReturnType(Ty); 10830 } 10831 10832 ABIArgInfo VEABIInfo::classifyArgumentType(QualType Ty) const { 10833 if (Ty->isAnyComplexType()) 10834 return ABIArgInfo::getDirect(); 10835 uint64_t Size = getContext().getTypeSize(Ty); 10836 if (Size < 64 && Ty->isIntegerType()) 10837 return ABIArgInfo::getExtend(Ty); 10838 return DefaultABIInfo::classifyArgumentType(Ty); 10839 } 10840 10841 void VEABIInfo::computeInfo(CGFunctionInfo &FI) const { 10842 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 10843 for (auto &Arg : FI.arguments()) 10844 Arg.info = classifyArgumentType(Arg.type); 10845 } 10846 10847 namespace { 10848 class VETargetCodeGenInfo : public TargetCodeGenInfo { 10849 public: 10850 VETargetCodeGenInfo(CodeGenTypes &CGT) 10851 : TargetCodeGenInfo(std::make_unique<VEABIInfo>(CGT)) {} 10852 // VE ABI requires the arguments of variadic and prototype-less functions 10853 // are passed in both registers and memory. 10854 bool isNoProtoCallVariadic(const CallArgList &args, 10855 const FunctionNoProtoType *fnType) const override { 10856 return true; 10857 } 10858 }; 10859 } // end anonymous namespace 10860 10861 //===----------------------------------------------------------------------===// 10862 // Driver code 10863 //===----------------------------------------------------------------------===// 10864 10865 bool CodeGenModule::supportsCOMDAT() const { 10866 return getTriple().supportsCOMDAT(); 10867 } 10868 10869 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 10870 if (TheTargetCodeGenInfo) 10871 return *TheTargetCodeGenInfo; 10872 10873 // Helper to set the unique_ptr while still keeping the return value. 10874 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & { 10875 this->TheTargetCodeGenInfo.reset(P); 10876 return *P; 10877 }; 10878 10879 const llvm::Triple &Triple = getTarget().getTriple(); 10880 switch (Triple.getArch()) { 10881 default: 10882 return SetCGInfo(new DefaultTargetCodeGenInfo(Types)); 10883 10884 case llvm::Triple::le32: 10885 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 10886 case llvm::Triple::mips: 10887 case llvm::Triple::mipsel: 10888 if (Triple.getOS() == llvm::Triple::NaCl) 10889 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 10890 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true)); 10891 10892 case llvm::Triple::mips64: 10893 case llvm::Triple::mips64el: 10894 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false)); 10895 10896 case llvm::Triple::avr: 10897 return SetCGInfo(new AVRTargetCodeGenInfo(Types)); 10898 10899 case llvm::Triple::aarch64: 10900 case llvm::Triple::aarch64_32: 10901 case llvm::Triple::aarch64_be: { 10902 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS; 10903 if (getTarget().getABI() == "darwinpcs") 10904 Kind = AArch64ABIInfo::DarwinPCS; 10905 else if (Triple.isOSWindows()) 10906 return SetCGInfo( 10907 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64)); 10908 10909 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind)); 10910 } 10911 10912 case llvm::Triple::wasm32: 10913 case llvm::Triple::wasm64: { 10914 WebAssemblyABIInfo::ABIKind Kind = WebAssemblyABIInfo::MVP; 10915 if (getTarget().getABI() == "experimental-mv") 10916 Kind = WebAssemblyABIInfo::ExperimentalMV; 10917 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types, Kind)); 10918 } 10919 10920 case llvm::Triple::arm: 10921 case llvm::Triple::armeb: 10922 case llvm::Triple::thumb: 10923 case llvm::Triple::thumbeb: { 10924 if (Triple.getOS() == llvm::Triple::Win32) { 10925 return SetCGInfo( 10926 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP)); 10927 } 10928 10929 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; 10930 StringRef ABIStr = getTarget().getABI(); 10931 if (ABIStr == "apcs-gnu") 10932 Kind = ARMABIInfo::APCS; 10933 else if (ABIStr == "aapcs16") 10934 Kind = ARMABIInfo::AAPCS16_VFP; 10935 else if (CodeGenOpts.FloatABI == "hard" || 10936 (CodeGenOpts.FloatABI != "soft" && 10937 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF || 10938 Triple.getEnvironment() == llvm::Triple::MuslEABIHF || 10939 Triple.getEnvironment() == llvm::Triple::EABIHF))) 10940 Kind = ARMABIInfo::AAPCS_VFP; 10941 10942 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind)); 10943 } 10944 10945 case llvm::Triple::ppc: { 10946 if (Triple.isOSAIX()) 10947 return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ false)); 10948 10949 bool IsSoftFloat = 10950 CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe"); 10951 bool RetSmallStructInRegABI = 10952 PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 10953 return SetCGInfo( 10954 new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI)); 10955 } 10956 case llvm::Triple::ppc64: 10957 if (Triple.isOSAIX()) 10958 return SetCGInfo(new AIXTargetCodeGenInfo(Types, /*Is64Bit*/ true)); 10959 10960 if (Triple.isOSBinFormatELF()) { 10961 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1; 10962 if (getTarget().getABI() == "elfv2") 10963 Kind = PPC64_SVR4_ABIInfo::ELFv2; 10964 bool HasQPX = getTarget().getABI() == "elfv1-qpx"; 10965 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 10966 10967 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX, 10968 IsSoftFloat)); 10969 } 10970 return SetCGInfo(new PPC64TargetCodeGenInfo(Types)); 10971 case llvm::Triple::ppc64le: { 10972 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 10973 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2; 10974 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx") 10975 Kind = PPC64_SVR4_ABIInfo::ELFv1; 10976 bool HasQPX = getTarget().getABI() == "elfv1-qpx"; 10977 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 10978 10979 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX, 10980 IsSoftFloat)); 10981 } 10982 10983 case llvm::Triple::nvptx: 10984 case llvm::Triple::nvptx64: 10985 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types)); 10986 10987 case llvm::Triple::msp430: 10988 return SetCGInfo(new MSP430TargetCodeGenInfo(Types)); 10989 10990 case llvm::Triple::riscv32: 10991 case llvm::Triple::riscv64: { 10992 StringRef ABIStr = getTarget().getABI(); 10993 unsigned XLen = getTarget().getPointerWidth(0); 10994 unsigned ABIFLen = 0; 10995 if (ABIStr.endswith("f")) 10996 ABIFLen = 32; 10997 else if (ABIStr.endswith("d")) 10998 ABIFLen = 64; 10999 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen)); 11000 } 11001 11002 case llvm::Triple::systemz: { 11003 bool SoftFloat = CodeGenOpts.FloatABI == "soft"; 11004 bool HasVector = !SoftFloat && getTarget().getABI() == "vector"; 11005 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector, SoftFloat)); 11006 } 11007 11008 case llvm::Triple::tce: 11009 case llvm::Triple::tcele: 11010 return SetCGInfo(new TCETargetCodeGenInfo(Types)); 11011 11012 case llvm::Triple::x86: { 11013 bool IsDarwinVectorABI = Triple.isOSDarwin(); 11014 bool RetSmallStructInRegABI = 11015 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 11016 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); 11017 11018 if (Triple.getOS() == llvm::Triple::Win32) { 11019 return SetCGInfo(new WinX86_32TargetCodeGenInfo( 11020 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 11021 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters)); 11022 } else { 11023 return SetCGInfo(new X86_32TargetCodeGenInfo( 11024 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 11025 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters, 11026 CodeGenOpts.FloatABI == "soft")); 11027 } 11028 } 11029 11030 case llvm::Triple::x86_64: { 11031 StringRef ABI = getTarget().getABI(); 11032 X86AVXABILevel AVXLevel = 11033 (ABI == "avx512" 11034 ? X86AVXABILevel::AVX512 11035 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None); 11036 11037 switch (Triple.getOS()) { 11038 case llvm::Triple::Win32: 11039 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel)); 11040 default: 11041 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel)); 11042 } 11043 } 11044 case llvm::Triple::hexagon: 11045 return SetCGInfo(new HexagonTargetCodeGenInfo(Types)); 11046 case llvm::Triple::lanai: 11047 return SetCGInfo(new LanaiTargetCodeGenInfo(Types)); 11048 case llvm::Triple::r600: 11049 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 11050 case llvm::Triple::amdgcn: 11051 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 11052 case llvm::Triple::sparc: 11053 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types)); 11054 case llvm::Triple::sparcv9: 11055 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types)); 11056 case llvm::Triple::xcore: 11057 return SetCGInfo(new XCoreTargetCodeGenInfo(Types)); 11058 case llvm::Triple::arc: 11059 return SetCGInfo(new ARCTargetCodeGenInfo(Types)); 11060 case llvm::Triple::spir: 11061 case llvm::Triple::spir64: 11062 return SetCGInfo(new SPIRTargetCodeGenInfo(Types)); 11063 case llvm::Triple::ve: 11064 return SetCGInfo(new VETargetCodeGenInfo(Types)); 11065 } 11066 } 11067 11068 /// Create an OpenCL kernel for an enqueued block. 11069 /// 11070 /// The kernel has the same function type as the block invoke function. Its 11071 /// name is the name of the block invoke function postfixed with "_kernel". 11072 /// It simply calls the block invoke function then returns. 11073 llvm::Function * 11074 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF, 11075 llvm::Function *Invoke, 11076 llvm::Value *BlockLiteral) const { 11077 auto *InvokeFT = Invoke->getFunctionType(); 11078 llvm::SmallVector<llvm::Type *, 2> ArgTys; 11079 for (auto &P : InvokeFT->params()) 11080 ArgTys.push_back(P); 11081 auto &C = CGF.getLLVMContext(); 11082 std::string Name = Invoke->getName().str() + "_kernel"; 11083 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 11084 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 11085 &CGF.CGM.getModule()); 11086 auto IP = CGF.Builder.saveIP(); 11087 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 11088 auto &Builder = CGF.Builder; 11089 Builder.SetInsertPoint(BB); 11090 llvm::SmallVector<llvm::Value *, 2> Args; 11091 for (auto &A : F->args()) 11092 Args.push_back(&A); 11093 Builder.CreateCall(Invoke, Args); 11094 Builder.CreateRetVoid(); 11095 Builder.restoreIP(IP); 11096 return F; 11097 } 11098 11099 /// Create an OpenCL kernel for an enqueued block. 11100 /// 11101 /// The type of the first argument (the block literal) is the struct type 11102 /// of the block literal instead of a pointer type. The first argument 11103 /// (block literal) is passed directly by value to the kernel. The kernel 11104 /// allocates the same type of struct on stack and stores the block literal 11105 /// to it and passes its pointer to the block invoke function. The kernel 11106 /// has "enqueued-block" function attribute and kernel argument metadata. 11107 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel( 11108 CodeGenFunction &CGF, llvm::Function *Invoke, 11109 llvm::Value *BlockLiteral) const { 11110 auto &Builder = CGF.Builder; 11111 auto &C = CGF.getLLVMContext(); 11112 11113 auto *BlockTy = BlockLiteral->getType()->getPointerElementType(); 11114 auto *InvokeFT = Invoke->getFunctionType(); 11115 llvm::SmallVector<llvm::Type *, 2> ArgTys; 11116 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals; 11117 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals; 11118 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames; 11119 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames; 11120 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals; 11121 llvm::SmallVector<llvm::Metadata *, 8> ArgNames; 11122 11123 ArgTys.push_back(BlockTy); 11124 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 11125 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0))); 11126 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 11127 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 11128 AccessQuals.push_back(llvm::MDString::get(C, "none")); 11129 ArgNames.push_back(llvm::MDString::get(C, "block_literal")); 11130 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) { 11131 ArgTys.push_back(InvokeFT->getParamType(I)); 11132 ArgTypeNames.push_back(llvm::MDString::get(C, "void*")); 11133 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3))); 11134 AccessQuals.push_back(llvm::MDString::get(C, "none")); 11135 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*")); 11136 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 11137 ArgNames.push_back( 11138 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str())); 11139 } 11140 std::string Name = Invoke->getName().str() + "_kernel"; 11141 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 11142 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 11143 &CGF.CGM.getModule()); 11144 F->addFnAttr("enqueued-block"); 11145 auto IP = CGF.Builder.saveIP(); 11146 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 11147 Builder.SetInsertPoint(BB); 11148 const auto BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlign(BlockTy); 11149 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr); 11150 BlockPtr->setAlignment(BlockAlign); 11151 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign); 11152 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0)); 11153 llvm::SmallVector<llvm::Value *, 2> Args; 11154 Args.push_back(Cast); 11155 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I) 11156 Args.push_back(I); 11157 Builder.CreateCall(Invoke, Args); 11158 Builder.CreateRetVoid(); 11159 Builder.restoreIP(IP); 11160 11161 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals)); 11162 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals)); 11163 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames)); 11164 F->setMetadata("kernel_arg_base_type", 11165 llvm::MDNode::get(C, ArgBaseTypeNames)); 11166 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals)); 11167 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata) 11168 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames)); 11169 11170 return F; 11171 } 11172