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