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