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