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 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DestTy); 453 } 454 455 llvm::Constant * 456 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src, 457 LangAS SrcAddr, LangAS DestAddr, 458 llvm::Type *DestTy) const { 459 // Since target may map different address spaces in AST to the same address 460 // space, an address space conversion may end up as a bitcast. 461 return llvm::ConstantExpr::getPointerCast(Src, DestTy); 462 } 463 464 llvm::SyncScope::ID 465 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 466 SyncScope Scope, 467 llvm::AtomicOrdering Ordering, 468 llvm::LLVMContext &Ctx) const { 469 return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */ 470 } 471 472 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays); 473 474 /// isEmptyField - Return true iff a the field is "empty", that is it 475 /// is an unnamed bit-field or an (array of) empty record(s). 476 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD, 477 bool AllowArrays) { 478 if (FD->isUnnamedBitfield()) 479 return true; 480 481 QualType FT = FD->getType(); 482 483 // Constant arrays of empty records count as empty, strip them off. 484 // Constant arrays of zero length always count as empty. 485 if (AllowArrays) 486 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 487 if (AT->getSize() == 0) 488 return true; 489 FT = AT->getElementType(); 490 } 491 492 const RecordType *RT = FT->getAs<RecordType>(); 493 if (!RT) 494 return false; 495 496 // C++ record fields are never empty, at least in the Itanium ABI. 497 // 498 // FIXME: We should use a predicate for whether this behavior is true in the 499 // current ABI. 500 if (isa<CXXRecordDecl>(RT->getDecl())) 501 return false; 502 503 return isEmptyRecord(Context, FT, AllowArrays); 504 } 505 506 /// isEmptyRecord - Return true iff a structure contains only empty 507 /// fields. Note that a structure with a flexible array member is not 508 /// considered empty. 509 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) { 510 const RecordType *RT = T->getAs<RecordType>(); 511 if (!RT) 512 return false; 513 const RecordDecl *RD = RT->getDecl(); 514 if (RD->hasFlexibleArrayMember()) 515 return false; 516 517 // If this is a C++ record, check the bases first. 518 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 519 for (const auto &I : CXXRD->bases()) 520 if (!isEmptyRecord(Context, I.getType(), true)) 521 return false; 522 523 for (const auto *I : RD->fields()) 524 if (!isEmptyField(Context, I, AllowArrays)) 525 return false; 526 return true; 527 } 528 529 /// isSingleElementStruct - Determine if a structure is a "single 530 /// element struct", i.e. it has exactly one non-empty field or 531 /// exactly one field which is itself a single element 532 /// struct. Structures with flexible array members are never 533 /// considered single element structs. 534 /// 535 /// \return The field declaration for the single non-empty field, if 536 /// it exists. 537 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) { 538 const RecordType *RT = T->getAs<RecordType>(); 539 if (!RT) 540 return nullptr; 541 542 const RecordDecl *RD = RT->getDecl(); 543 if (RD->hasFlexibleArrayMember()) 544 return nullptr; 545 546 const Type *Found = nullptr; 547 548 // If this is a C++ record, check the bases first. 549 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 550 for (const auto &I : CXXRD->bases()) { 551 // Ignore empty records. 552 if (isEmptyRecord(Context, I.getType(), true)) 553 continue; 554 555 // If we already found an element then this isn't a single-element struct. 556 if (Found) 557 return nullptr; 558 559 // If this is non-empty and not a single element struct, the composite 560 // cannot be a single element struct. 561 Found = isSingleElementStruct(I.getType(), Context); 562 if (!Found) 563 return nullptr; 564 } 565 } 566 567 // Check for single element. 568 for (const auto *FD : RD->fields()) { 569 QualType FT = FD->getType(); 570 571 // Ignore empty fields. 572 if (isEmptyField(Context, FD, true)) 573 continue; 574 575 // If we already found an element then this isn't a single-element 576 // struct. 577 if (Found) 578 return nullptr; 579 580 // Treat single element arrays as the element. 581 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) { 582 if (AT->getSize().getZExtValue() != 1) 583 break; 584 FT = AT->getElementType(); 585 } 586 587 if (!isAggregateTypeForABI(FT)) { 588 Found = FT.getTypePtr(); 589 } else { 590 Found = isSingleElementStruct(FT, Context); 591 if (!Found) 592 return nullptr; 593 } 594 } 595 596 // We don't consider a struct a single-element struct if it has 597 // padding beyond the element type. 598 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T)) 599 return nullptr; 600 601 return Found; 602 } 603 604 namespace { 605 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty, 606 const ABIArgInfo &AI) { 607 // This default implementation defers to the llvm backend's va_arg 608 // instruction. It can handle only passing arguments directly 609 // (typically only handled in the backend for primitive types), or 610 // aggregates passed indirectly by pointer (NOTE: if the "byval" 611 // flag has ABI impact in the callee, this implementation cannot 612 // work.) 613 614 // Only a few cases are covered here at the moment -- those needed 615 // by the default abi. 616 llvm::Value *Val; 617 618 if (AI.isIndirect()) { 619 assert(!AI.getPaddingType() && 620 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 621 assert( 622 !AI.getIndirectRealign() && 623 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!"); 624 625 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty); 626 CharUnits TyAlignForABI = TyInfo.second; 627 628 llvm::Type *BaseTy = 629 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty)); 630 llvm::Value *Addr = 631 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy); 632 return Address(Addr, TyAlignForABI); 633 } else { 634 assert((AI.isDirect() || AI.isExtend()) && 635 "Unexpected ArgInfo Kind in generic VAArg emitter!"); 636 637 assert(!AI.getInReg() && 638 "Unexpected InReg seen in arginfo in generic VAArg emitter!"); 639 assert(!AI.getPaddingType() && 640 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!"); 641 assert(!AI.getDirectOffset() && 642 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!"); 643 assert(!AI.getCoerceToType() && 644 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!"); 645 646 Address Temp = CGF.CreateMemTemp(Ty, "varet"); 647 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty)); 648 CGF.Builder.CreateStore(Val, Temp); 649 return Temp; 650 } 651 } 652 653 /// DefaultABIInfo - The default implementation for ABI specific 654 /// details. This implementation provides information which results in 655 /// self-consistent and sensible LLVM IR generation, but does not 656 /// conform to any particular ABI. 657 class DefaultABIInfo : public ABIInfo { 658 public: 659 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 660 661 ABIArgInfo classifyReturnType(QualType RetTy) const; 662 ABIArgInfo classifyArgumentType(QualType RetTy) const; 663 664 void computeInfo(CGFunctionInfo &FI) const override { 665 if (!getCXXABI().classifyReturnType(FI)) 666 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 667 for (auto &I : FI.arguments()) 668 I.info = classifyArgumentType(I.type); 669 } 670 671 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 672 QualType Ty) const override { 673 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty)); 674 } 675 }; 676 677 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo { 678 public: 679 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 680 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 681 }; 682 683 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const { 684 Ty = useFirstFieldIfTransparentUnion(Ty); 685 686 if (isAggregateTypeForABI(Ty)) { 687 // Records with non-trivial destructors/copy-constructors should not be 688 // passed by value. 689 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 690 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 691 692 return getNaturalAlignIndirect(Ty); 693 } 694 695 // Treat an enum type as its underlying type. 696 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 697 Ty = EnumTy->getDecl()->getIntegerType(); 698 699 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 700 : ABIArgInfo::getDirect()); 701 } 702 703 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const { 704 if (RetTy->isVoidType()) 705 return ABIArgInfo::getIgnore(); 706 707 if (isAggregateTypeForABI(RetTy)) 708 return getNaturalAlignIndirect(RetTy); 709 710 // Treat an enum type as its underlying type. 711 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 712 RetTy = EnumTy->getDecl()->getIntegerType(); 713 714 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 715 : ABIArgInfo::getDirect()); 716 } 717 718 //===----------------------------------------------------------------------===// 719 // WebAssembly ABI Implementation 720 // 721 // This is a very simple ABI that relies a lot on DefaultABIInfo. 722 //===----------------------------------------------------------------------===// 723 724 class WebAssemblyABIInfo final : public SwiftABIInfo { 725 DefaultABIInfo defaultInfo; 726 727 public: 728 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT) 729 : SwiftABIInfo(CGT), defaultInfo(CGT) {} 730 731 private: 732 ABIArgInfo classifyReturnType(QualType RetTy) const; 733 ABIArgInfo classifyArgumentType(QualType Ty) const; 734 735 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 736 // non-virtual, but computeInfo and EmitVAArg are virtual, so we 737 // overload them. 738 void computeInfo(CGFunctionInfo &FI) const override { 739 if (!getCXXABI().classifyReturnType(FI)) 740 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 741 for (auto &Arg : FI.arguments()) 742 Arg.info = classifyArgumentType(Arg.type); 743 } 744 745 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 746 QualType Ty) const override; 747 748 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 749 bool asReturnValue) const override { 750 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 751 } 752 753 bool isSwiftErrorInRegister() const override { 754 return false; 755 } 756 }; 757 758 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo { 759 public: 760 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 761 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {} 762 763 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 764 CodeGen::CodeGenModule &CGM) const override { 765 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 766 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 767 if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) { 768 llvm::Function *Fn = cast<llvm::Function>(GV); 769 llvm::AttrBuilder B; 770 B.addAttribute("wasm-import-module", Attr->getImportModule()); 771 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 772 } 773 if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) { 774 llvm::Function *Fn = cast<llvm::Function>(GV); 775 llvm::AttrBuilder B; 776 B.addAttribute("wasm-import-name", Attr->getImportName()); 777 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B); 778 } 779 } 780 781 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) { 782 llvm::Function *Fn = cast<llvm::Function>(GV); 783 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype()) 784 Fn->addFnAttr("no-prototype"); 785 } 786 } 787 }; 788 789 /// Classify argument of given type \p Ty. 790 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const { 791 Ty = useFirstFieldIfTransparentUnion(Ty); 792 793 if (isAggregateTypeForABI(Ty)) { 794 // Records with non-trivial destructors/copy-constructors should not be 795 // passed by value. 796 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 797 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 798 // Ignore empty structs/unions. 799 if (isEmptyRecord(getContext(), Ty, true)) 800 return ABIArgInfo::getIgnore(); 801 // Lower single-element structs to just pass a regular value. TODO: We 802 // could do reasonable-size multiple-element structs too, using getExpand(), 803 // though watch out for things like bitfields. 804 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 805 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 806 } 807 808 // Otherwise just do the default thing. 809 return defaultInfo.classifyArgumentType(Ty); 810 } 811 812 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const { 813 if (isAggregateTypeForABI(RetTy)) { 814 // Records with non-trivial destructors/copy-constructors should not be 815 // returned by value. 816 if (!getRecordArgABI(RetTy, getCXXABI())) { 817 // Ignore empty structs/unions. 818 if (isEmptyRecord(getContext(), RetTy, true)) 819 return ABIArgInfo::getIgnore(); 820 // Lower single-element structs to just return a regular value. TODO: We 821 // could do reasonable-size multiple-element structs too, using 822 // ABIArgInfo::getDirect(). 823 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 824 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 825 } 826 } 827 828 // Otherwise just do the default thing. 829 return defaultInfo.classifyReturnType(RetTy); 830 } 831 832 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 833 QualType Ty) const { 834 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false, 835 getContext().getTypeInfoInChars(Ty), 836 CharUnits::fromQuantity(4), 837 /*AllowHigherAlign=*/ true); 838 } 839 840 //===----------------------------------------------------------------------===// 841 // le32/PNaCl bitcode ABI Implementation 842 // 843 // This is a simplified version of the x86_32 ABI. Arguments and return values 844 // are always passed on the stack. 845 //===----------------------------------------------------------------------===// 846 847 class PNaClABIInfo : public ABIInfo { 848 public: 849 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {} 850 851 ABIArgInfo classifyReturnType(QualType RetTy) const; 852 ABIArgInfo classifyArgumentType(QualType RetTy) const; 853 854 void computeInfo(CGFunctionInfo &FI) const override; 855 Address EmitVAArg(CodeGenFunction &CGF, 856 Address VAListAddr, QualType Ty) const override; 857 }; 858 859 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo { 860 public: 861 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 862 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {} 863 }; 864 865 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const { 866 if (!getCXXABI().classifyReturnType(FI)) 867 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 868 869 for (auto &I : FI.arguments()) 870 I.info = classifyArgumentType(I.type); 871 } 872 873 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 874 QualType Ty) const { 875 // The PNaCL ABI is a bit odd, in that varargs don't use normal 876 // function classification. Structs get passed directly for varargs 877 // functions, through a rewriting transform in 878 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows 879 // this target to actually support a va_arg instructions with an 880 // aggregate type, unlike other targets. 881 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect()); 882 } 883 884 /// Classify argument of given type \p Ty. 885 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const { 886 if (isAggregateTypeForABI(Ty)) { 887 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 888 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 889 return getNaturalAlignIndirect(Ty); 890 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) { 891 // Treat an enum type as its underlying type. 892 Ty = EnumTy->getDecl()->getIntegerType(); 893 } else if (Ty->isFloatingType()) { 894 // Floating-point types don't go inreg. 895 return ABIArgInfo::getDirect(); 896 } 897 898 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 899 : ABIArgInfo::getDirect()); 900 } 901 902 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const { 903 if (RetTy->isVoidType()) 904 return ABIArgInfo::getIgnore(); 905 906 // In the PNaCl ABI we always return records/structures on the stack. 907 if (isAggregateTypeForABI(RetTy)) 908 return getNaturalAlignIndirect(RetTy); 909 910 // Treat an enum type as its underlying type. 911 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 912 RetTy = EnumTy->getDecl()->getIntegerType(); 913 914 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 915 : ABIArgInfo::getDirect()); 916 } 917 918 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 919 StringRef Constraint, 920 llvm::Type* Ty) { 921 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint) 922 .Cases("y", "&y", "^Ym", true) 923 .Default(false); 924 if (IsMMXCons && Ty->isVectorTy()) { 925 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) { 926 // Invalid MMX constraint 927 return nullptr; 928 } 929 930 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext()); 931 } 932 933 // No operation needed 934 return Ty; 935 } 936 937 /// Returns true if this type can be passed in SSE registers with the 938 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64. 939 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) { 940 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 941 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) { 942 if (BT->getKind() == BuiltinType::LongDouble) { 943 if (&Context.getTargetInfo().getLongDoubleFormat() == 944 &llvm::APFloat::x87DoubleExtended()) 945 return false; 946 } 947 return true; 948 } 949 } else if (const VectorType *VT = Ty->getAs<VectorType>()) { 950 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX 951 // registers specially. 952 unsigned VecSize = Context.getTypeSize(VT); 953 if (VecSize == 128 || VecSize == 256 || VecSize == 512) 954 return true; 955 } 956 return false; 957 } 958 959 /// Returns true if this aggregate is small enough to be passed in SSE registers 960 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64. 961 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) { 962 return NumMembers <= 4; 963 } 964 965 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86. 966 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) { 967 auto AI = ABIArgInfo::getDirect(T); 968 AI.setInReg(true); 969 AI.setCanBeFlattened(false); 970 return AI; 971 } 972 973 //===----------------------------------------------------------------------===// 974 // X86-32 ABI Implementation 975 //===----------------------------------------------------------------------===// 976 977 /// Similar to llvm::CCState, but for Clang. 978 struct CCState { 979 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {} 980 981 unsigned CC; 982 unsigned FreeRegs; 983 unsigned FreeSSERegs; 984 }; 985 986 enum { 987 // Vectorcall only allows the first 6 parameters to be passed in registers. 988 VectorcallMaxParamNumAsReg = 6 989 }; 990 991 /// X86_32ABIInfo - The X86-32 ABI information. 992 class X86_32ABIInfo : public SwiftABIInfo { 993 enum Class { 994 Integer, 995 Float 996 }; 997 998 static const unsigned MinABIStackAlignInBytes = 4; 999 1000 bool IsDarwinVectorABI; 1001 bool IsRetSmallStructInRegABI; 1002 bool IsWin32StructABI; 1003 bool IsSoftFloatABI; 1004 bool IsMCUABI; 1005 unsigned DefaultNumRegisterParameters; 1006 bool IsMMXEnabled; 1007 1008 static bool isRegisterSize(unsigned Size) { 1009 return (Size == 8 || Size == 16 || Size == 32 || Size == 64); 1010 } 1011 1012 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 1013 // FIXME: Assumes vectorcall is in use. 1014 return isX86VectorTypeForVectorCall(getContext(), Ty); 1015 } 1016 1017 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 1018 uint64_t NumMembers) const override { 1019 // FIXME: Assumes vectorcall is in use. 1020 return isX86VectorCallAggregateSmallEnough(NumMembers); 1021 } 1022 1023 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const; 1024 1025 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 1026 /// such that the argument will be passed in memory. 1027 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 1028 1029 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const; 1030 1031 /// Return the alignment to use for the given type on the stack. 1032 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const; 1033 1034 Class classify(QualType Ty) const; 1035 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const; 1036 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 1037 1038 /// Updates the number of available free registers, returns 1039 /// true if any registers were allocated. 1040 bool updateFreeRegs(QualType Ty, CCState &State) const; 1041 1042 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg, 1043 bool &NeedsPadding) const; 1044 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const; 1045 1046 bool canExpandIndirectArgument(QualType Ty) const; 1047 1048 /// Rewrite the function info so that all memory arguments use 1049 /// inalloca. 1050 void rewriteWithInAlloca(CGFunctionInfo &FI) const; 1051 1052 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1053 CharUnits &StackOffset, ABIArgInfo &Info, 1054 QualType Type) const; 1055 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State, 1056 bool &UsedInAlloca) const; 1057 1058 public: 1059 1060 void computeInfo(CGFunctionInfo &FI) const override; 1061 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 1062 QualType Ty) const override; 1063 1064 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1065 bool RetSmallStructInRegABI, bool Win32StructABI, 1066 unsigned NumRegisterParameters, bool SoftFloatABI, 1067 bool MMXEnabled) 1068 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI), 1069 IsRetSmallStructInRegABI(RetSmallStructInRegABI), 1070 IsWin32StructABI(Win32StructABI), 1071 IsSoftFloatABI(SoftFloatABI), 1072 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()), 1073 DefaultNumRegisterParameters(NumRegisterParameters), 1074 IsMMXEnabled(MMXEnabled) {} 1075 1076 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 1077 bool asReturnValue) const override { 1078 // LLVM's x86-32 lowering currently only assigns up to three 1079 // integer registers and three fp registers. Oddly, it'll use up to 1080 // four vector registers for vectors, but those can overlap with the 1081 // scalar registers. 1082 return occupiesMoreThan(CGT, scalars, /*total*/ 3); 1083 } 1084 1085 bool isSwiftErrorInRegister() const override { 1086 // x86-32 lowering does not support passing swifterror in a register. 1087 return false; 1088 } 1089 1090 bool isPassInMMXRegABI() const { 1091 // The System V i386 psABI requires __m64 to be passed in MMX registers. 1092 // Clang historically had a bug where it failed to apply this rule, and 1093 // some platforms (e.g. Darwin, PS4, and FreeBSD) have opted to maintain 1094 // compatibility with the old Clang behavior, so we only apply it on 1095 // platforms that have specifically requested it (currently just Linux and 1096 // NetBSD). 1097 const llvm::Triple &T = getTarget().getTriple(); 1098 if (IsMMXEnabled && (T.isOSLinux() || T.isOSNetBSD())) 1099 return true; 1100 return false; 1101 } 1102 }; 1103 1104 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo { 1105 public: 1106 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI, 1107 bool RetSmallStructInRegABI, bool Win32StructABI, 1108 unsigned NumRegisterParameters, bool SoftFloatABI, 1109 bool MMXEnabled = false) 1110 : TargetCodeGenInfo(new X86_32ABIInfo( 1111 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI, 1112 NumRegisterParameters, SoftFloatABI, MMXEnabled)) {} 1113 1114 static bool isStructReturnInRegABI( 1115 const llvm::Triple &Triple, const CodeGenOptions &Opts); 1116 1117 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 1118 CodeGen::CodeGenModule &CGM) const override; 1119 1120 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 1121 // Darwin uses different dwarf register numbers for EH. 1122 if (CGM.getTarget().getTriple().isOSDarwin()) return 5; 1123 return 4; 1124 } 1125 1126 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 1127 llvm::Value *Address) const override; 1128 1129 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 1130 StringRef Constraint, 1131 llvm::Type* Ty) const override { 1132 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 1133 } 1134 1135 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue, 1136 std::string &Constraints, 1137 std::vector<llvm::Type *> &ResultRegTypes, 1138 std::vector<llvm::Type *> &ResultTruncRegTypes, 1139 std::vector<LValue> &ResultRegDests, 1140 std::string &AsmString, 1141 unsigned NumOutputs) const override; 1142 1143 llvm::Constant * 1144 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 1145 unsigned Sig = (0xeb << 0) | // jmp rel8 1146 (0x06 << 8) | // .+0x08 1147 ('v' << 16) | 1148 ('2' << 24); 1149 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 1150 } 1151 1152 StringRef getARCRetainAutoreleasedReturnValueMarker() const override { 1153 return "movl\t%ebp, %ebp" 1154 "\t\t// marker for objc_retainAutoreleaseReturnValue"; 1155 } 1156 }; 1157 1158 } 1159 1160 /// Rewrite input constraint references after adding some output constraints. 1161 /// In the case where there is one output and one input and we add one output, 1162 /// we need to replace all operand references greater than or equal to 1: 1163 /// mov $0, $1 1164 /// mov eax, $1 1165 /// The result will be: 1166 /// mov $0, $2 1167 /// mov eax, $2 1168 static void rewriteInputConstraintReferences(unsigned FirstIn, 1169 unsigned NumNewOuts, 1170 std::string &AsmString) { 1171 std::string Buf; 1172 llvm::raw_string_ostream OS(Buf); 1173 size_t Pos = 0; 1174 while (Pos < AsmString.size()) { 1175 size_t DollarStart = AsmString.find('$', Pos); 1176 if (DollarStart == std::string::npos) 1177 DollarStart = AsmString.size(); 1178 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart); 1179 if (DollarEnd == std::string::npos) 1180 DollarEnd = AsmString.size(); 1181 OS << StringRef(&AsmString[Pos], DollarEnd - Pos); 1182 Pos = DollarEnd; 1183 size_t NumDollars = DollarEnd - DollarStart; 1184 if (NumDollars % 2 != 0 && Pos < AsmString.size()) { 1185 // We have an operand reference. 1186 size_t DigitStart = Pos; 1187 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart); 1188 if (DigitEnd == std::string::npos) 1189 DigitEnd = AsmString.size(); 1190 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart); 1191 unsigned OperandIndex; 1192 if (!OperandStr.getAsInteger(10, OperandIndex)) { 1193 if (OperandIndex >= FirstIn) 1194 OperandIndex += NumNewOuts; 1195 OS << OperandIndex; 1196 } else { 1197 OS << OperandStr; 1198 } 1199 Pos = DigitEnd; 1200 } 1201 } 1202 AsmString = std::move(OS.str()); 1203 } 1204 1205 /// Add output constraints for EAX:EDX because they are return registers. 1206 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs( 1207 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints, 1208 std::vector<llvm::Type *> &ResultRegTypes, 1209 std::vector<llvm::Type *> &ResultTruncRegTypes, 1210 std::vector<LValue> &ResultRegDests, std::string &AsmString, 1211 unsigned NumOutputs) const { 1212 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType()); 1213 1214 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is 1215 // larger. 1216 if (!Constraints.empty()) 1217 Constraints += ','; 1218 if (RetWidth <= 32) { 1219 Constraints += "={eax}"; 1220 ResultRegTypes.push_back(CGF.Int32Ty); 1221 } else { 1222 // Use the 'A' constraint for EAX:EDX. 1223 Constraints += "=A"; 1224 ResultRegTypes.push_back(CGF.Int64Ty); 1225 } 1226 1227 // Truncate EAX or EAX:EDX to an integer of the appropriate size. 1228 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth); 1229 ResultTruncRegTypes.push_back(CoerceTy); 1230 1231 // Coerce the integer by bitcasting the return slot pointer. 1232 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(), 1233 CoerceTy->getPointerTo())); 1234 ResultRegDests.push_back(ReturnSlot); 1235 1236 rewriteInputConstraintReferences(NumOutputs, 1, AsmString); 1237 } 1238 1239 /// shouldReturnTypeInRegister - Determine if the given type should be 1240 /// returned in a register (for the Darwin and MCU ABI). 1241 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty, 1242 ASTContext &Context) const { 1243 uint64_t Size = Context.getTypeSize(Ty); 1244 1245 // For i386, type must be register sized. 1246 // For the MCU ABI, it only needs to be <= 8-byte 1247 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size))) 1248 return false; 1249 1250 if (Ty->isVectorType()) { 1251 // 64- and 128- bit vectors inside structures are not returned in 1252 // registers. 1253 if (Size == 64 || Size == 128) 1254 return false; 1255 1256 return true; 1257 } 1258 1259 // If this is a builtin, pointer, enum, complex type, member pointer, or 1260 // member function pointer it is ok. 1261 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() || 1262 Ty->isAnyComplexType() || Ty->isEnumeralType() || 1263 Ty->isBlockPointerType() || Ty->isMemberPointerType()) 1264 return true; 1265 1266 // Arrays are treated like records. 1267 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) 1268 return shouldReturnTypeInRegister(AT->getElementType(), Context); 1269 1270 // Otherwise, it must be a record type. 1271 const RecordType *RT = Ty->getAs<RecordType>(); 1272 if (!RT) return false; 1273 1274 // FIXME: Traverse bases here too. 1275 1276 // Structure types are passed in register if all fields would be 1277 // passed in a register. 1278 for (const auto *FD : RT->getDecl()->fields()) { 1279 // Empty fields are ignored. 1280 if (isEmptyField(Context, FD, true)) 1281 continue; 1282 1283 // Check fields recursively. 1284 if (!shouldReturnTypeInRegister(FD->getType(), Context)) 1285 return false; 1286 } 1287 return true; 1288 } 1289 1290 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) { 1291 // Treat complex types as the element type. 1292 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) 1293 Ty = CTy->getElementType(); 1294 1295 // Check for a type which we know has a simple scalar argument-passing 1296 // convention without any padding. (We're specifically looking for 32 1297 // and 64-bit integer and integer-equivalents, float, and double.) 1298 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() && 1299 !Ty->isEnumeralType() && !Ty->isBlockPointerType()) 1300 return false; 1301 1302 uint64_t Size = Context.getTypeSize(Ty); 1303 return Size == 32 || Size == 64; 1304 } 1305 1306 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD, 1307 uint64_t &Size) { 1308 for (const auto *FD : RD->fields()) { 1309 // Scalar arguments on the stack get 4 byte alignment on x86. If the 1310 // argument is smaller than 32-bits, expanding the struct will create 1311 // alignment padding. 1312 if (!is32Or64BitBasicType(FD->getType(), Context)) 1313 return false; 1314 1315 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know 1316 // how to expand them yet, and the predicate for telling if a bitfield still 1317 // counts as "basic" is more complicated than what we were doing previously. 1318 if (FD->isBitField()) 1319 return false; 1320 1321 Size += Context.getTypeSize(FD->getType()); 1322 } 1323 return true; 1324 } 1325 1326 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD, 1327 uint64_t &Size) { 1328 // Don't do this if there are any non-empty bases. 1329 for (const CXXBaseSpecifier &Base : RD->bases()) { 1330 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(), 1331 Size)) 1332 return false; 1333 } 1334 if (!addFieldSizes(Context, RD, Size)) 1335 return false; 1336 return true; 1337 } 1338 1339 /// Test whether an argument type which is to be passed indirectly (on the 1340 /// stack) would have the equivalent layout if it was expanded into separate 1341 /// arguments. If so, we prefer to do the latter to avoid inhibiting 1342 /// optimizations. 1343 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const { 1344 // We can only expand structure types. 1345 const RecordType *RT = Ty->getAs<RecordType>(); 1346 if (!RT) 1347 return false; 1348 const RecordDecl *RD = RT->getDecl(); 1349 uint64_t Size = 0; 1350 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 1351 if (!IsWin32StructABI) { 1352 // On non-Windows, we have to conservatively match our old bitcode 1353 // prototypes in order to be ABI-compatible at the bitcode level. 1354 if (!CXXRD->isCLike()) 1355 return false; 1356 } else { 1357 // Don't do this for dynamic classes. 1358 if (CXXRD->isDynamicClass()) 1359 return false; 1360 } 1361 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size)) 1362 return false; 1363 } else { 1364 if (!addFieldSizes(getContext(), RD, Size)) 1365 return false; 1366 } 1367 1368 // We can do this if there was no alignment padding. 1369 return Size == getContext().getTypeSize(Ty); 1370 } 1371 1372 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const { 1373 // If the return value is indirect, then the hidden argument is consuming one 1374 // integer register. 1375 if (State.FreeRegs) { 1376 --State.FreeRegs; 1377 if (!IsMCUABI) 1378 return getNaturalAlignIndirectInReg(RetTy); 1379 } 1380 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false); 1381 } 1382 1383 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy, 1384 CCState &State) const { 1385 if (RetTy->isVoidType()) 1386 return ABIArgInfo::getIgnore(); 1387 1388 const Type *Base = nullptr; 1389 uint64_t NumElts = 0; 1390 if ((State.CC == llvm::CallingConv::X86_VectorCall || 1391 State.CC == llvm::CallingConv::X86_RegCall) && 1392 isHomogeneousAggregate(RetTy, Base, NumElts)) { 1393 // The LLVM struct type for such an aggregate should lower properly. 1394 return ABIArgInfo::getDirect(); 1395 } 1396 1397 if (const VectorType *VT = RetTy->getAs<VectorType>()) { 1398 uint64_t Size = getContext().getTypeSize(RetTy); 1399 // On Darwin, some vectors are returned in registers. 1400 if (IsDarwinVectorABI) { 1401 // 128-bit vectors are a special case; they are returned in 1402 // registers and we need to make sure to pick a type the LLVM 1403 // backend will like. 1404 if (Size == 128) 1405 return ABIArgInfo::getDirect(llvm::VectorType::get( 1406 llvm::Type::getInt64Ty(getVMContext()), 2)); 1407 1408 // Always return in register if it fits in a general purpose 1409 // register, or if it is 64 bits and has a single element. 1410 if ((Size == 8 || Size == 16 || Size == 32) || 1411 (Size == 64 && VT->getNumElements() == 1)) 1412 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 1413 Size)); 1414 1415 return getIndirectReturnResult(RetTy, State); 1416 } 1417 1418 if (VT->getElementType()->isIntegerType() && Size == 64 && 1419 isPassInMMXRegABI()) 1420 return ABIArgInfo::getDirect(llvm::Type::getX86_MMXTy(getVMContext())); 1421 1422 return ABIArgInfo::getDirect(); 1423 } 1424 1425 if (isAggregateTypeForABI(RetTy)) { 1426 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 1427 // Structures with flexible arrays are always indirect. 1428 if (RT->getDecl()->hasFlexibleArrayMember()) 1429 return getIndirectReturnResult(RetTy, State); 1430 } 1431 1432 // If specified, structs and unions are always indirect. 1433 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType()) 1434 return getIndirectReturnResult(RetTy, State); 1435 1436 // Ignore empty structs/unions. 1437 if (isEmptyRecord(getContext(), RetTy, true)) 1438 return ABIArgInfo::getIgnore(); 1439 1440 // Small structures which are register sized are generally returned 1441 // in a register. 1442 if (shouldReturnTypeInRegister(RetTy, getContext())) { 1443 uint64_t Size = getContext().getTypeSize(RetTy); 1444 1445 // As a special-case, if the struct is a "single-element" struct, and 1446 // the field is of type "float" or "double", return it in a 1447 // floating-point register. (MSVC does not apply this special case.) 1448 // We apply a similar transformation for pointer types to improve the 1449 // quality of the generated IR. 1450 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 1451 if ((!IsWin32StructABI && SeltTy->isRealFloatingType()) 1452 || SeltTy->hasPointerRepresentation()) 1453 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 1454 1455 // FIXME: We should be able to narrow this integer in cases with dead 1456 // padding. 1457 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size)); 1458 } 1459 1460 return getIndirectReturnResult(RetTy, State); 1461 } 1462 1463 // Treat an enum type as its underlying type. 1464 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 1465 RetTy = EnumTy->getDecl()->getIntegerType(); 1466 1467 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 1468 : ABIArgInfo::getDirect()); 1469 } 1470 1471 static bool isSSEVectorType(ASTContext &Context, QualType Ty) { 1472 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128; 1473 } 1474 1475 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) { 1476 const RecordType *RT = Ty->getAs<RecordType>(); 1477 if (!RT) 1478 return 0; 1479 const RecordDecl *RD = RT->getDecl(); 1480 1481 // If this is a C++ record, check the bases first. 1482 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 1483 for (const auto &I : CXXRD->bases()) 1484 if (!isRecordWithSSEVectorType(Context, I.getType())) 1485 return false; 1486 1487 for (const auto *i : RD->fields()) { 1488 QualType FT = i->getType(); 1489 1490 if (isSSEVectorType(Context, FT)) 1491 return true; 1492 1493 if (isRecordWithSSEVectorType(Context, FT)) 1494 return true; 1495 } 1496 1497 return false; 1498 } 1499 1500 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty, 1501 unsigned Align) const { 1502 // Otherwise, if the alignment is less than or equal to the minimum ABI 1503 // alignment, just use the default; the backend will handle this. 1504 if (Align <= MinABIStackAlignInBytes) 1505 return 0; // Use default alignment. 1506 1507 // On non-Darwin, the stack type alignment is always 4. 1508 if (!IsDarwinVectorABI) { 1509 // Set explicit alignment, since we may need to realign the top. 1510 return MinABIStackAlignInBytes; 1511 } 1512 1513 // Otherwise, if the type contains an SSE vector type, the alignment is 16. 1514 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) || 1515 isRecordWithSSEVectorType(getContext(), Ty))) 1516 return 16; 1517 1518 return MinABIStackAlignInBytes; 1519 } 1520 1521 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal, 1522 CCState &State) const { 1523 if (!ByVal) { 1524 if (State.FreeRegs) { 1525 --State.FreeRegs; // Non-byval indirects just use one pointer. 1526 if (!IsMCUABI) 1527 return getNaturalAlignIndirectInReg(Ty); 1528 } 1529 return getNaturalAlignIndirect(Ty, false); 1530 } 1531 1532 // Compute the byval alignment. 1533 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 1534 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign); 1535 if (StackAlign == 0) 1536 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true); 1537 1538 // If the stack alignment is less than the type alignment, realign the 1539 // argument. 1540 bool Realign = TypeAlign > StackAlign; 1541 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign), 1542 /*ByVal=*/true, Realign); 1543 } 1544 1545 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const { 1546 const Type *T = isSingleElementStruct(Ty, getContext()); 1547 if (!T) 1548 T = Ty.getTypePtr(); 1549 1550 if (const BuiltinType *BT = T->getAs<BuiltinType>()) { 1551 BuiltinType::Kind K = BT->getKind(); 1552 if (K == BuiltinType::Float || K == BuiltinType::Double) 1553 return Float; 1554 } 1555 return Integer; 1556 } 1557 1558 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const { 1559 if (!IsSoftFloatABI) { 1560 Class C = classify(Ty); 1561 if (C == Float) 1562 return false; 1563 } 1564 1565 unsigned Size = getContext().getTypeSize(Ty); 1566 unsigned SizeInRegs = (Size + 31) / 32; 1567 1568 if (SizeInRegs == 0) 1569 return false; 1570 1571 if (!IsMCUABI) { 1572 if (SizeInRegs > State.FreeRegs) { 1573 State.FreeRegs = 0; 1574 return false; 1575 } 1576 } else { 1577 // The MCU psABI allows passing parameters in-reg even if there are 1578 // earlier parameters that are passed on the stack. Also, 1579 // it does not allow passing >8-byte structs in-register, 1580 // even if there are 3 free registers available. 1581 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2) 1582 return false; 1583 } 1584 1585 State.FreeRegs -= SizeInRegs; 1586 return true; 1587 } 1588 1589 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State, 1590 bool &InReg, 1591 bool &NeedsPadding) const { 1592 // On Windows, aggregates other than HFAs are never passed in registers, and 1593 // they do not consume register slots. Homogenous floating-point aggregates 1594 // (HFAs) have already been dealt with at this point. 1595 if (IsWin32StructABI && isAggregateTypeForABI(Ty)) 1596 return false; 1597 1598 NeedsPadding = false; 1599 InReg = !IsMCUABI; 1600 1601 if (!updateFreeRegs(Ty, State)) 1602 return false; 1603 1604 if (IsMCUABI) 1605 return true; 1606 1607 if (State.CC == llvm::CallingConv::X86_FastCall || 1608 State.CC == llvm::CallingConv::X86_VectorCall || 1609 State.CC == llvm::CallingConv::X86_RegCall) { 1610 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs) 1611 NeedsPadding = true; 1612 1613 return false; 1614 } 1615 1616 return true; 1617 } 1618 1619 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const { 1620 if (!updateFreeRegs(Ty, State)) 1621 return false; 1622 1623 if (IsMCUABI) 1624 return false; 1625 1626 if (State.CC == llvm::CallingConv::X86_FastCall || 1627 State.CC == llvm::CallingConv::X86_VectorCall || 1628 State.CC == llvm::CallingConv::X86_RegCall) { 1629 if (getContext().getTypeSize(Ty) > 32) 1630 return false; 1631 1632 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() || 1633 Ty->isReferenceType()); 1634 } 1635 1636 return true; 1637 } 1638 1639 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty, 1640 CCState &State) const { 1641 // FIXME: Set alignment on indirect arguments. 1642 1643 Ty = useFirstFieldIfTransparentUnion(Ty); 1644 1645 // Check with the C++ ABI first. 1646 const RecordType *RT = Ty->getAs<RecordType>(); 1647 if (RT) { 1648 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 1649 if (RAA == CGCXXABI::RAA_Indirect) { 1650 return getIndirectResult(Ty, false, State); 1651 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 1652 // The field index doesn't matter, we'll fix it up later. 1653 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0); 1654 } 1655 } 1656 1657 // Regcall uses the concept of a homogenous vector aggregate, similar 1658 // to other targets. 1659 const Type *Base = nullptr; 1660 uint64_t NumElts = 0; 1661 if (State.CC == llvm::CallingConv::X86_RegCall && 1662 isHomogeneousAggregate(Ty, Base, NumElts)) { 1663 1664 if (State.FreeSSERegs >= NumElts) { 1665 State.FreeSSERegs -= NumElts; 1666 if (Ty->isBuiltinType() || Ty->isVectorType()) 1667 return ABIArgInfo::getDirect(); 1668 return ABIArgInfo::getExpand(); 1669 } 1670 return getIndirectResult(Ty, /*ByVal=*/false, State); 1671 } 1672 1673 if (isAggregateTypeForABI(Ty)) { 1674 // Structures with flexible arrays are always indirect. 1675 // FIXME: This should not be byval! 1676 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 1677 return getIndirectResult(Ty, true, State); 1678 1679 // Ignore empty structs/unions on non-Windows. 1680 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true)) 1681 return ABIArgInfo::getIgnore(); 1682 1683 llvm::LLVMContext &LLVMContext = getVMContext(); 1684 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 1685 bool NeedsPadding = false; 1686 bool InReg; 1687 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) { 1688 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 1689 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32); 1690 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 1691 if (InReg) 1692 return ABIArgInfo::getDirectInReg(Result); 1693 else 1694 return ABIArgInfo::getDirect(Result); 1695 } 1696 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr; 1697 1698 // Expand small (<= 128-bit) record types when we know that the stack layout 1699 // of those arguments will match the struct. This is important because the 1700 // LLVM backend isn't smart enough to remove byval, which inhibits many 1701 // optimizations. 1702 // Don't do this for the MCU if there are still free integer registers 1703 // (see X86_64 ABI for full explanation). 1704 if (getContext().getTypeSize(Ty) <= 4 * 32 && 1705 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty)) 1706 return ABIArgInfo::getExpandWithPadding( 1707 State.CC == llvm::CallingConv::X86_FastCall || 1708 State.CC == llvm::CallingConv::X86_VectorCall || 1709 State.CC == llvm::CallingConv::X86_RegCall, 1710 PaddingType); 1711 1712 return getIndirectResult(Ty, true, State); 1713 } 1714 1715 if (const VectorType *VT = Ty->getAs<VectorType>()) { 1716 uint64_t Size = getContext().getTypeSize(Ty); 1717 // On Darwin, some vectors are passed in memory, we handle this by passing 1718 // it as an i8/i16/i32/i64. 1719 if (IsDarwinVectorABI) { 1720 if ((Size == 8 || Size == 16 || Size == 32) || 1721 (Size == 64 && VT->getNumElements() == 1)) 1722 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 1723 Size)); 1724 } 1725 1726 if (VT->getElementType()->isIntegerType() && Size == 64) { 1727 if (isPassInMMXRegABI()) 1728 return ABIArgInfo::getDirect(llvm::Type::getX86_MMXTy(getVMContext())); 1729 else 1730 return ABIArgInfo::getDirect( 1731 llvm::IntegerType::get(getVMContext(), 64)); 1732 } 1733 return ABIArgInfo::getDirect(); 1734 } 1735 1736 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 1737 Ty = EnumTy->getDecl()->getIntegerType(); 1738 1739 bool InReg = shouldPrimitiveUseInReg(Ty, State); 1740 1741 if (Ty->isPromotableIntegerType()) { 1742 if (InReg) 1743 return ABIArgInfo::getExtendInReg(Ty); 1744 return ABIArgInfo::getExtend(Ty); 1745 } 1746 1747 if (InReg) 1748 return ABIArgInfo::getDirectInReg(); 1749 return ABIArgInfo::getDirect(); 1750 } 1751 1752 void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State, 1753 bool &UsedInAlloca) const { 1754 // Vectorcall x86 works subtly different than in x64, so the format is 1755 // a bit different than the x64 version. First, all vector types (not HVAs) 1756 // are assigned, with the first 6 ending up in the YMM0-5 or XMM0-5 registers. 1757 // This differs from the x64 implementation, where the first 6 by INDEX get 1758 // registers. 1759 // After that, integers AND HVAs are assigned Left to Right in the same pass. 1760 // Integers are passed as ECX/EDX if one is available (in order). HVAs will 1761 // first take up the remaining YMM/XMM registers. If insufficient registers 1762 // remain but an integer register (ECX/EDX) is available, it will be passed 1763 // in that, else, on the stack. 1764 for (auto &I : FI.arguments()) { 1765 // First pass do all the vector types. 1766 const Type *Base = nullptr; 1767 uint64_t NumElts = 0; 1768 const QualType& Ty = I.type; 1769 if ((Ty->isVectorType() || Ty->isBuiltinType()) && 1770 isHomogeneousAggregate(Ty, Base, NumElts)) { 1771 if (State.FreeSSERegs >= NumElts) { 1772 State.FreeSSERegs -= NumElts; 1773 I.info = ABIArgInfo::getDirect(); 1774 } else { 1775 I.info = classifyArgumentType(Ty, State); 1776 } 1777 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca); 1778 } 1779 } 1780 1781 for (auto &I : FI.arguments()) { 1782 // Second pass, do the rest! 1783 const Type *Base = nullptr; 1784 uint64_t NumElts = 0; 1785 const QualType& Ty = I.type; 1786 bool IsHva = isHomogeneousAggregate(Ty, Base, NumElts); 1787 1788 if (IsHva && !Ty->isVectorType() && !Ty->isBuiltinType()) { 1789 // Assign true HVAs (non vector/native FP types). 1790 if (State.FreeSSERegs >= NumElts) { 1791 State.FreeSSERegs -= NumElts; 1792 I.info = getDirectX86Hva(); 1793 } else { 1794 I.info = getIndirectResult(Ty, /*ByVal=*/false, State); 1795 } 1796 } else if (!IsHva) { 1797 // Assign all Non-HVAs, so this will exclude Vector/FP args. 1798 I.info = classifyArgumentType(Ty, State); 1799 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca); 1800 } 1801 } 1802 } 1803 1804 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const { 1805 CCState State(FI.getCallingConvention()); 1806 if (IsMCUABI) 1807 State.FreeRegs = 3; 1808 else if (State.CC == llvm::CallingConv::X86_FastCall) 1809 State.FreeRegs = 2; 1810 else if (State.CC == llvm::CallingConv::X86_VectorCall) { 1811 State.FreeRegs = 2; 1812 State.FreeSSERegs = 6; 1813 } else if (FI.getHasRegParm()) 1814 State.FreeRegs = FI.getRegParm(); 1815 else if (State.CC == llvm::CallingConv::X86_RegCall) { 1816 State.FreeRegs = 5; 1817 State.FreeSSERegs = 8; 1818 } else 1819 State.FreeRegs = DefaultNumRegisterParameters; 1820 1821 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 1822 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State); 1823 } else if (FI.getReturnInfo().isIndirect()) { 1824 // The C++ ABI is not aware of register usage, so we have to check if the 1825 // return value was sret and put it in a register ourselves if appropriate. 1826 if (State.FreeRegs) { 1827 --State.FreeRegs; // The sret parameter consumes a register. 1828 if (!IsMCUABI) 1829 FI.getReturnInfo().setInReg(true); 1830 } 1831 } 1832 1833 // The chain argument effectively gives us another free register. 1834 if (FI.isChainCall()) 1835 ++State.FreeRegs; 1836 1837 bool UsedInAlloca = false; 1838 if (State.CC == llvm::CallingConv::X86_VectorCall) { 1839 computeVectorCallArgs(FI, State, UsedInAlloca); 1840 } else { 1841 // If not vectorcall, revert to normal behavior. 1842 for (auto &I : FI.arguments()) { 1843 I.info = classifyArgumentType(I.type, State); 1844 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca); 1845 } 1846 } 1847 1848 // If we needed to use inalloca for any argument, do a second pass and rewrite 1849 // all the memory arguments to use inalloca. 1850 if (UsedInAlloca) 1851 rewriteWithInAlloca(FI); 1852 } 1853 1854 void 1855 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields, 1856 CharUnits &StackOffset, ABIArgInfo &Info, 1857 QualType Type) const { 1858 // Arguments are always 4-byte-aligned. 1859 CharUnits FieldAlign = CharUnits::fromQuantity(4); 1860 1861 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct"); 1862 Info = ABIArgInfo::getInAlloca(FrameFields.size()); 1863 FrameFields.push_back(CGT.ConvertTypeForMem(Type)); 1864 StackOffset += getContext().getTypeSizeInChars(Type); 1865 1866 // Insert padding bytes to respect alignment. 1867 CharUnits FieldEnd = StackOffset; 1868 StackOffset = FieldEnd.alignTo(FieldAlign); 1869 if (StackOffset != FieldEnd) { 1870 CharUnits NumBytes = StackOffset - FieldEnd; 1871 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext()); 1872 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity()); 1873 FrameFields.push_back(Ty); 1874 } 1875 } 1876 1877 static bool isArgInAlloca(const ABIArgInfo &Info) { 1878 // Leave ignored and inreg arguments alone. 1879 switch (Info.getKind()) { 1880 case ABIArgInfo::InAlloca: 1881 return true; 1882 case ABIArgInfo::Indirect: 1883 assert(Info.getIndirectByVal()); 1884 return true; 1885 case ABIArgInfo::Ignore: 1886 return false; 1887 case ABIArgInfo::Direct: 1888 case ABIArgInfo::Extend: 1889 if (Info.getInReg()) 1890 return false; 1891 return true; 1892 case ABIArgInfo::Expand: 1893 case ABIArgInfo::CoerceAndExpand: 1894 // These are aggregate types which are never passed in registers when 1895 // inalloca is involved. 1896 return true; 1897 } 1898 llvm_unreachable("invalid enum"); 1899 } 1900 1901 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const { 1902 assert(IsWin32StructABI && "inalloca only supported on win32"); 1903 1904 // Build a packed struct type for all of the arguments in memory. 1905 SmallVector<llvm::Type *, 6> FrameFields; 1906 1907 // The stack alignment is always 4. 1908 CharUnits StackAlign = CharUnits::fromQuantity(4); 1909 1910 CharUnits StackOffset; 1911 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end(); 1912 1913 // Put 'this' into the struct before 'sret', if necessary. 1914 bool IsThisCall = 1915 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall; 1916 ABIArgInfo &Ret = FI.getReturnInfo(); 1917 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall && 1918 isArgInAlloca(I->info)) { 1919 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 1920 ++I; 1921 } 1922 1923 // Put the sret parameter into the inalloca struct if it's in memory. 1924 if (Ret.isIndirect() && !Ret.getInReg()) { 1925 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType()); 1926 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy); 1927 // On Windows, the hidden sret parameter is always returned in eax. 1928 Ret.setInAllocaSRet(IsWin32StructABI); 1929 } 1930 1931 // Skip the 'this' parameter in ecx. 1932 if (IsThisCall) 1933 ++I; 1934 1935 // Put arguments passed in memory into the struct. 1936 for (; I != E; ++I) { 1937 if (isArgInAlloca(I->info)) 1938 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type); 1939 } 1940 1941 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields, 1942 /*isPacked=*/true), 1943 StackAlign); 1944 } 1945 1946 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF, 1947 Address VAListAddr, QualType Ty) const { 1948 1949 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 1950 1951 // x86-32 changes the alignment of certain arguments on the stack. 1952 // 1953 // Just messing with TypeInfo like this works because we never pass 1954 // anything indirectly. 1955 TypeInfo.second = CharUnits::fromQuantity( 1956 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity())); 1957 1958 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false, 1959 TypeInfo, CharUnits::fromQuantity(4), 1960 /*AllowHigherAlign*/ true); 1961 } 1962 1963 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI( 1964 const llvm::Triple &Triple, const CodeGenOptions &Opts) { 1965 assert(Triple.getArch() == llvm::Triple::x86); 1966 1967 switch (Opts.getStructReturnConvention()) { 1968 case CodeGenOptions::SRCK_Default: 1969 break; 1970 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return 1971 return false; 1972 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return 1973 return true; 1974 } 1975 1976 if (Triple.isOSDarwin() || Triple.isOSIAMCU()) 1977 return true; 1978 1979 switch (Triple.getOS()) { 1980 case llvm::Triple::DragonFly: 1981 case llvm::Triple::FreeBSD: 1982 case llvm::Triple::OpenBSD: 1983 case llvm::Triple::Win32: 1984 return true; 1985 default: 1986 return false; 1987 } 1988 } 1989 1990 void X86_32TargetCodeGenInfo::setTargetAttributes( 1991 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 1992 if (GV->isDeclaration()) 1993 return; 1994 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 1995 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 1996 llvm::Function *Fn = cast<llvm::Function>(GV); 1997 Fn->addFnAttr("stackrealign"); 1998 } 1999 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2000 llvm::Function *Fn = cast<llvm::Function>(GV); 2001 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2002 } 2003 } 2004 } 2005 2006 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable( 2007 CodeGen::CodeGenFunction &CGF, 2008 llvm::Value *Address) const { 2009 CodeGen::CGBuilderTy &Builder = CGF.Builder; 2010 2011 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 2012 2013 // 0-7 are the eight integer registers; the order is different 2014 // on Darwin (for EH), but the range is the same. 2015 // 8 is %eip. 2016 AssignToArrayRange(Builder, Address, Four8, 0, 8); 2017 2018 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) { 2019 // 12-16 are st(0..4). Not sure why we stop at 4. 2020 // These have size 16, which is sizeof(long double) on 2021 // platforms with 8-byte alignment for that type. 2022 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16); 2023 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16); 2024 2025 } else { 2026 // 9 is %eflags, which doesn't get a size on Darwin for some 2027 // reason. 2028 Builder.CreateAlignedStore( 2029 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9), 2030 CharUnits::One()); 2031 2032 // 11-16 are st(0..5). Not sure why we stop at 5. 2033 // These have size 12, which is sizeof(long double) on 2034 // platforms with 4-byte alignment for that type. 2035 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12); 2036 AssignToArrayRange(Builder, Address, Twelve8, 11, 16); 2037 } 2038 2039 return false; 2040 } 2041 2042 //===----------------------------------------------------------------------===// 2043 // X86-64 ABI Implementation 2044 //===----------------------------------------------------------------------===// 2045 2046 2047 namespace { 2048 /// The AVX ABI level for X86 targets. 2049 enum class X86AVXABILevel { 2050 None, 2051 AVX, 2052 AVX512 2053 }; 2054 2055 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel. 2056 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) { 2057 switch (AVXLevel) { 2058 case X86AVXABILevel::AVX512: 2059 return 512; 2060 case X86AVXABILevel::AVX: 2061 return 256; 2062 case X86AVXABILevel::None: 2063 return 128; 2064 } 2065 llvm_unreachable("Unknown AVXLevel"); 2066 } 2067 2068 /// X86_64ABIInfo - The X86_64 ABI information. 2069 class X86_64ABIInfo : public SwiftABIInfo { 2070 enum Class { 2071 Integer = 0, 2072 SSE, 2073 SSEUp, 2074 X87, 2075 X87Up, 2076 ComplexX87, 2077 NoClass, 2078 Memory 2079 }; 2080 2081 /// merge - Implement the X86_64 ABI merging algorithm. 2082 /// 2083 /// Merge an accumulating classification \arg Accum with a field 2084 /// classification \arg Field. 2085 /// 2086 /// \param Accum - The accumulating classification. This should 2087 /// always be either NoClass or the result of a previous merge 2088 /// call. In addition, this should never be Memory (the caller 2089 /// should just return Memory for the aggregate). 2090 static Class merge(Class Accum, Class Field); 2091 2092 /// postMerge - Implement the X86_64 ABI post merging algorithm. 2093 /// 2094 /// Post merger cleanup, reduces a malformed Hi and Lo pair to 2095 /// final MEMORY or SSE classes when necessary. 2096 /// 2097 /// \param AggregateSize - The size of the current aggregate in 2098 /// the classification process. 2099 /// 2100 /// \param Lo - The classification for the parts of the type 2101 /// residing in the low word of the containing object. 2102 /// 2103 /// \param Hi - The classification for the parts of the type 2104 /// residing in the higher words of the containing object. 2105 /// 2106 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const; 2107 2108 /// classify - Determine the x86_64 register classes in which the 2109 /// given type T should be passed. 2110 /// 2111 /// \param Lo - The classification for the parts of the type 2112 /// residing in the low word of the containing object. 2113 /// 2114 /// \param Hi - The classification for the parts of the type 2115 /// residing in the high word of the containing object. 2116 /// 2117 /// \param OffsetBase - The bit offset of this type in the 2118 /// containing object. Some parameters are classified different 2119 /// depending on whether they straddle an eightbyte boundary. 2120 /// 2121 /// \param isNamedArg - Whether the argument in question is a "named" 2122 /// argument, as used in AMD64-ABI 3.5.7. 2123 /// 2124 /// If a word is unused its result will be NoClass; if a type should 2125 /// be passed in Memory then at least the classification of \arg Lo 2126 /// will be Memory. 2127 /// 2128 /// The \arg Lo class will be NoClass iff the argument is ignored. 2129 /// 2130 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will 2131 /// also be ComplexX87. 2132 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi, 2133 bool isNamedArg) const; 2134 2135 llvm::Type *GetByteVectorType(QualType Ty) const; 2136 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType, 2137 unsigned IROffset, QualType SourceTy, 2138 unsigned SourceOffset) const; 2139 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType, 2140 unsigned IROffset, QualType SourceTy, 2141 unsigned SourceOffset) const; 2142 2143 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2144 /// such that the argument will be returned in memory. 2145 ABIArgInfo getIndirectReturnResult(QualType Ty) const; 2146 2147 /// getIndirectResult - Give a source type \arg Ty, return a suitable result 2148 /// such that the argument will be passed in memory. 2149 /// 2150 /// \param freeIntRegs - The number of free integer registers remaining 2151 /// available. 2152 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const; 2153 2154 ABIArgInfo classifyReturnType(QualType RetTy) const; 2155 2156 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs, 2157 unsigned &neededInt, unsigned &neededSSE, 2158 bool isNamedArg) const; 2159 2160 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt, 2161 unsigned &NeededSSE) const; 2162 2163 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 2164 unsigned &NeededSSE) const; 2165 2166 bool IsIllegalVectorType(QualType Ty) const; 2167 2168 /// The 0.98 ABI revision clarified a lot of ambiguities, 2169 /// unfortunately in ways that were not always consistent with 2170 /// certain previous compilers. In particular, platforms which 2171 /// required strict binary compatibility with older versions of GCC 2172 /// may need to exempt themselves. 2173 bool honorsRevision0_98() const { 2174 return !getTarget().getTriple().isOSDarwin(); 2175 } 2176 2177 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to 2178 /// classify it as INTEGER (for compatibility with older clang compilers). 2179 bool classifyIntegerMMXAsSSE() const { 2180 // Clang <= 3.8 did not do this. 2181 if (getContext().getLangOpts().getClangABICompat() <= 2182 LangOptions::ClangABI::Ver3_8) 2183 return false; 2184 2185 const llvm::Triple &Triple = getTarget().getTriple(); 2186 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4) 2187 return false; 2188 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10) 2189 return false; 2190 return true; 2191 } 2192 2193 X86AVXABILevel AVXLevel; 2194 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on 2195 // 64-bit hardware. 2196 bool Has64BitPointers; 2197 2198 public: 2199 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) : 2200 SwiftABIInfo(CGT), AVXLevel(AVXLevel), 2201 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) { 2202 } 2203 2204 bool isPassedUsingAVXType(QualType type) const { 2205 unsigned neededInt, neededSSE; 2206 // The freeIntRegs argument doesn't matter here. 2207 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE, 2208 /*isNamedArg*/true); 2209 if (info.isDirect()) { 2210 llvm::Type *ty = info.getCoerceToType(); 2211 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty)) 2212 return (vectorTy->getBitWidth() > 128); 2213 } 2214 return false; 2215 } 2216 2217 void computeInfo(CGFunctionInfo &FI) const override; 2218 2219 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2220 QualType Ty) const override; 2221 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 2222 QualType Ty) const override; 2223 2224 bool has64BitPointers() const { 2225 return Has64BitPointers; 2226 } 2227 2228 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 2229 bool asReturnValue) const override { 2230 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2231 } 2232 bool isSwiftErrorInRegister() const override { 2233 return true; 2234 } 2235 }; 2236 2237 /// WinX86_64ABIInfo - The Windows X86_64 ABI information. 2238 class WinX86_64ABIInfo : public SwiftABIInfo { 2239 public: 2240 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) 2241 : SwiftABIInfo(CGT), 2242 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {} 2243 2244 void computeInfo(CGFunctionInfo &FI) const override; 2245 2246 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 2247 QualType Ty) const override; 2248 2249 bool isHomogeneousAggregateBaseType(QualType Ty) const override { 2250 // FIXME: Assumes vectorcall is in use. 2251 return isX86VectorTypeForVectorCall(getContext(), Ty); 2252 } 2253 2254 bool isHomogeneousAggregateSmallEnough(const Type *Ty, 2255 uint64_t NumMembers) const override { 2256 // FIXME: Assumes vectorcall is in use. 2257 return isX86VectorCallAggregateSmallEnough(NumMembers); 2258 } 2259 2260 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars, 2261 bool asReturnValue) const override { 2262 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 2263 } 2264 2265 bool isSwiftErrorInRegister() const override { 2266 return true; 2267 } 2268 2269 private: 2270 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType, 2271 bool IsVectorCall, bool IsRegCall) const; 2272 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs, 2273 const ABIArgInfo ¤t) const; 2274 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs, 2275 bool IsVectorCall, bool IsRegCall) const; 2276 2277 bool IsMingw64; 2278 }; 2279 2280 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2281 public: 2282 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) 2283 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {} 2284 2285 const X86_64ABIInfo &getABIInfo() const { 2286 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo()); 2287 } 2288 2289 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks 2290 /// the autoreleaseRV/retainRV optimization. 2291 bool shouldSuppressTailCallsOfRetainAutoreleasedReturnValue() const override { 2292 return true; 2293 } 2294 2295 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2296 return 7; 2297 } 2298 2299 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2300 llvm::Value *Address) const override { 2301 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2302 2303 // 0-15 are the 16 integer registers. 2304 // 16 is %rip. 2305 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2306 return false; 2307 } 2308 2309 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF, 2310 StringRef Constraint, 2311 llvm::Type* Ty) const override { 2312 return X86AdjustInlineAsmType(CGF, Constraint, Ty); 2313 } 2314 2315 bool isNoProtoCallVariadic(const CallArgList &args, 2316 const FunctionNoProtoType *fnType) const override { 2317 // The default CC on x86-64 sets %al to the number of SSA 2318 // registers used, and GCC sets this when calling an unprototyped 2319 // function, so we override the default behavior. However, don't do 2320 // that when AVX types are involved: the ABI explicitly states it is 2321 // undefined, and it doesn't work in practice because of how the ABI 2322 // defines varargs anyway. 2323 if (fnType->getCallConv() == CC_C) { 2324 bool HasAVXType = false; 2325 for (CallArgList::const_iterator 2326 it = args.begin(), ie = args.end(); it != ie; ++it) { 2327 if (getABIInfo().isPassedUsingAVXType(it->Ty)) { 2328 HasAVXType = true; 2329 break; 2330 } 2331 } 2332 2333 if (!HasAVXType) 2334 return true; 2335 } 2336 2337 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType); 2338 } 2339 2340 llvm::Constant * 2341 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override { 2342 unsigned Sig = (0xeb << 0) | // jmp rel8 2343 (0x06 << 8) | // .+0x08 2344 ('v' << 16) | 2345 ('2' << 24); 2346 return llvm::ConstantInt::get(CGM.Int32Ty, Sig); 2347 } 2348 2349 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2350 CodeGen::CodeGenModule &CGM) const override { 2351 if (GV->isDeclaration()) 2352 return; 2353 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2354 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2355 llvm::Function *Fn = cast<llvm::Function>(GV); 2356 Fn->addFnAttr("stackrealign"); 2357 } 2358 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2359 llvm::Function *Fn = cast<llvm::Function>(GV); 2360 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2361 } 2362 } 2363 } 2364 }; 2365 2366 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) { 2367 // If the argument does not end in .lib, automatically add the suffix. 2368 // If the argument contains a space, enclose it in quotes. 2369 // This matches the behavior of MSVC. 2370 bool Quote = (Lib.find(" ") != StringRef::npos); 2371 std::string ArgStr = Quote ? "\"" : ""; 2372 ArgStr += Lib; 2373 if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a")) 2374 ArgStr += ".lib"; 2375 ArgStr += Quote ? "\"" : ""; 2376 return ArgStr; 2377 } 2378 2379 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo { 2380 public: 2381 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2382 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI, 2383 unsigned NumRegisterParameters) 2384 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI, 2385 Win32StructABI, NumRegisterParameters, false) {} 2386 2387 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2388 CodeGen::CodeGenModule &CGM) const override; 2389 2390 void getDependentLibraryOption(llvm::StringRef Lib, 2391 llvm::SmallString<24> &Opt) const override { 2392 Opt = "/DEFAULTLIB:"; 2393 Opt += qualifyWindowsLibrary(Lib); 2394 } 2395 2396 void getDetectMismatchOption(llvm::StringRef Name, 2397 llvm::StringRef Value, 2398 llvm::SmallString<32> &Opt) const override { 2399 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2400 } 2401 }; 2402 2403 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2404 CodeGen::CodeGenModule &CGM) { 2405 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) { 2406 2407 if (CGM.getCodeGenOpts().StackProbeSize != 4096) 2408 Fn->addFnAttr("stack-probe-size", 2409 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize)); 2410 if (CGM.getCodeGenOpts().NoStackArgProbe) 2411 Fn->addFnAttr("no-stack-arg-probe"); 2412 } 2413 } 2414 2415 void WinX86_32TargetCodeGenInfo::setTargetAttributes( 2416 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2417 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2418 if (GV->isDeclaration()) 2419 return; 2420 addStackProbeTargetAttributes(D, GV, CGM); 2421 } 2422 2423 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo { 2424 public: 2425 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, 2426 X86AVXABILevel AVXLevel) 2427 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {} 2428 2429 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 2430 CodeGen::CodeGenModule &CGM) const override; 2431 2432 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 2433 return 7; 2434 } 2435 2436 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 2437 llvm::Value *Address) const override { 2438 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8); 2439 2440 // 0-15 are the 16 integer registers. 2441 // 16 is %rip. 2442 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16); 2443 return false; 2444 } 2445 2446 void getDependentLibraryOption(llvm::StringRef Lib, 2447 llvm::SmallString<24> &Opt) const override { 2448 Opt = "/DEFAULTLIB:"; 2449 Opt += qualifyWindowsLibrary(Lib); 2450 } 2451 2452 void getDetectMismatchOption(llvm::StringRef Name, 2453 llvm::StringRef Value, 2454 llvm::SmallString<32> &Opt) const override { 2455 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\""; 2456 } 2457 }; 2458 2459 void WinX86_64TargetCodeGenInfo::setTargetAttributes( 2460 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const { 2461 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM); 2462 if (GV->isDeclaration()) 2463 return; 2464 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 2465 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) { 2466 llvm::Function *Fn = cast<llvm::Function>(GV); 2467 Fn->addFnAttr("stackrealign"); 2468 } 2469 if (FD->hasAttr<AnyX86InterruptAttr>()) { 2470 llvm::Function *Fn = cast<llvm::Function>(GV); 2471 Fn->setCallingConv(llvm::CallingConv::X86_INTR); 2472 } 2473 } 2474 2475 addStackProbeTargetAttributes(D, GV, CGM); 2476 } 2477 } 2478 2479 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo, 2480 Class &Hi) const { 2481 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done: 2482 // 2483 // (a) If one of the classes is Memory, the whole argument is passed in 2484 // memory. 2485 // 2486 // (b) If X87UP is not preceded by X87, the whole argument is passed in 2487 // memory. 2488 // 2489 // (c) If the size of the aggregate exceeds two eightbytes and the first 2490 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole 2491 // argument is passed in memory. NOTE: This is necessary to keep the 2492 // ABI working for processors that don't support the __m256 type. 2493 // 2494 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE. 2495 // 2496 // Some of these are enforced by the merging logic. Others can arise 2497 // only with unions; for example: 2498 // union { _Complex double; unsigned; } 2499 // 2500 // Note that clauses (b) and (c) were added in 0.98. 2501 // 2502 if (Hi == Memory) 2503 Lo = Memory; 2504 if (Hi == X87Up && Lo != X87 && honorsRevision0_98()) 2505 Lo = Memory; 2506 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp)) 2507 Lo = Memory; 2508 if (Hi == SSEUp && Lo != SSE) 2509 Hi = SSE; 2510 } 2511 2512 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) { 2513 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is 2514 // classified recursively so that always two fields are 2515 // considered. The resulting class is calculated according to 2516 // the classes of the fields in the eightbyte: 2517 // 2518 // (a) If both classes are equal, this is the resulting class. 2519 // 2520 // (b) If one of the classes is NO_CLASS, the resulting class is 2521 // the other class. 2522 // 2523 // (c) If one of the classes is MEMORY, the result is the MEMORY 2524 // class. 2525 // 2526 // (d) If one of the classes is INTEGER, the result is the 2527 // INTEGER. 2528 // 2529 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class, 2530 // MEMORY is used as class. 2531 // 2532 // (f) Otherwise class SSE is used. 2533 2534 // Accum should never be memory (we should have returned) or 2535 // ComplexX87 (because this cannot be passed in a structure). 2536 assert((Accum != Memory && Accum != ComplexX87) && 2537 "Invalid accumulated classification during merge."); 2538 if (Accum == Field || Field == NoClass) 2539 return Accum; 2540 if (Field == Memory) 2541 return Memory; 2542 if (Accum == NoClass) 2543 return Field; 2544 if (Accum == Integer || Field == Integer) 2545 return Integer; 2546 if (Field == X87 || Field == X87Up || Field == ComplexX87 || 2547 Accum == X87 || Accum == X87Up) 2548 return Memory; 2549 return SSE; 2550 } 2551 2552 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase, 2553 Class &Lo, Class &Hi, bool isNamedArg) const { 2554 // FIXME: This code can be simplified by introducing a simple value class for 2555 // Class pairs with appropriate constructor methods for the various 2556 // situations. 2557 2558 // FIXME: Some of the split computations are wrong; unaligned vectors 2559 // shouldn't be passed in registers for example, so there is no chance they 2560 // can straddle an eightbyte. Verify & simplify. 2561 2562 Lo = Hi = NoClass; 2563 2564 Class &Current = OffsetBase < 64 ? Lo : Hi; 2565 Current = Memory; 2566 2567 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 2568 BuiltinType::Kind k = BT->getKind(); 2569 2570 if (k == BuiltinType::Void) { 2571 Current = NoClass; 2572 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) { 2573 Lo = Integer; 2574 Hi = Integer; 2575 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) { 2576 Current = Integer; 2577 } else if (k == BuiltinType::Float || k == BuiltinType::Double) { 2578 Current = SSE; 2579 } else if (k == BuiltinType::LongDouble) { 2580 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2581 if (LDF == &llvm::APFloat::IEEEquad()) { 2582 Lo = SSE; 2583 Hi = SSEUp; 2584 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) { 2585 Lo = X87; 2586 Hi = X87Up; 2587 } else if (LDF == &llvm::APFloat::IEEEdouble()) { 2588 Current = SSE; 2589 } else 2590 llvm_unreachable("unexpected long double representation!"); 2591 } 2592 // FIXME: _Decimal32 and _Decimal64 are SSE. 2593 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp). 2594 return; 2595 } 2596 2597 if (const EnumType *ET = Ty->getAs<EnumType>()) { 2598 // Classify the underlying integer type. 2599 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg); 2600 return; 2601 } 2602 2603 if (Ty->hasPointerRepresentation()) { 2604 Current = Integer; 2605 return; 2606 } 2607 2608 if (Ty->isMemberPointerType()) { 2609 if (Ty->isMemberFunctionPointerType()) { 2610 if (Has64BitPointers) { 2611 // If Has64BitPointers, this is an {i64, i64}, so classify both 2612 // Lo and Hi now. 2613 Lo = Hi = Integer; 2614 } else { 2615 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that 2616 // straddles an eightbyte boundary, Hi should be classified as well. 2617 uint64_t EB_FuncPtr = (OffsetBase) / 64; 2618 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64; 2619 if (EB_FuncPtr != EB_ThisAdj) { 2620 Lo = Hi = Integer; 2621 } else { 2622 Current = Integer; 2623 } 2624 } 2625 } else { 2626 Current = Integer; 2627 } 2628 return; 2629 } 2630 2631 if (const VectorType *VT = Ty->getAs<VectorType>()) { 2632 uint64_t Size = getContext().getTypeSize(VT); 2633 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) { 2634 // gcc passes the following as integer: 2635 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float> 2636 // 2 bytes - <2 x char>, <1 x short> 2637 // 1 byte - <1 x char> 2638 Current = Integer; 2639 2640 // If this type crosses an eightbyte boundary, it should be 2641 // split. 2642 uint64_t EB_Lo = (OffsetBase) / 64; 2643 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64; 2644 if (EB_Lo != EB_Hi) 2645 Hi = Lo; 2646 } else if (Size == 64) { 2647 QualType ElementType = VT->getElementType(); 2648 2649 // gcc passes <1 x double> in memory. :( 2650 if (ElementType->isSpecificBuiltinType(BuiltinType::Double)) 2651 return; 2652 2653 // gcc passes <1 x long long> as SSE but clang used to unconditionally 2654 // pass them as integer. For platforms where clang is the de facto 2655 // platform compiler, we must continue to use integer. 2656 if (!classifyIntegerMMXAsSSE() && 2657 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) || 2658 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) || 2659 ElementType->isSpecificBuiltinType(BuiltinType::Long) || 2660 ElementType->isSpecificBuiltinType(BuiltinType::ULong))) 2661 Current = Integer; 2662 else 2663 Current = SSE; 2664 2665 // If this type crosses an eightbyte boundary, it should be 2666 // split. 2667 if (OffsetBase && OffsetBase != 64) 2668 Hi = Lo; 2669 } else if (Size == 128 || 2670 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) { 2671 // Arguments of 256-bits are split into four eightbyte chunks. The 2672 // least significant one belongs to class SSE and all the others to class 2673 // SSEUP. The original Lo and Hi design considers that types can't be 2674 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense. 2675 // This design isn't correct for 256-bits, but since there're no cases 2676 // where the upper parts would need to be inspected, avoid adding 2677 // complexity and just consider Hi to match the 64-256 part. 2678 // 2679 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in 2680 // registers if they are "named", i.e. not part of the "..." of a 2681 // variadic function. 2682 // 2683 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are 2684 // split into eight eightbyte chunks, one SSE and seven SSEUP. 2685 Lo = SSE; 2686 Hi = SSEUp; 2687 } 2688 return; 2689 } 2690 2691 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 2692 QualType ET = getContext().getCanonicalType(CT->getElementType()); 2693 2694 uint64_t Size = getContext().getTypeSize(Ty); 2695 if (ET->isIntegralOrEnumerationType()) { 2696 if (Size <= 64) 2697 Current = Integer; 2698 else if (Size <= 128) 2699 Lo = Hi = Integer; 2700 } else if (ET == getContext().FloatTy) { 2701 Current = SSE; 2702 } else if (ET == getContext().DoubleTy) { 2703 Lo = Hi = SSE; 2704 } else if (ET == getContext().LongDoubleTy) { 2705 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 2706 if (LDF == &llvm::APFloat::IEEEquad()) 2707 Current = Memory; 2708 else if (LDF == &llvm::APFloat::x87DoubleExtended()) 2709 Current = ComplexX87; 2710 else if (LDF == &llvm::APFloat::IEEEdouble()) 2711 Lo = Hi = SSE; 2712 else 2713 llvm_unreachable("unexpected long double representation!"); 2714 } 2715 2716 // If this complex type crosses an eightbyte boundary then it 2717 // should be split. 2718 uint64_t EB_Real = (OffsetBase) / 64; 2719 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64; 2720 if (Hi == NoClass && EB_Real != EB_Imag) 2721 Hi = Lo; 2722 2723 return; 2724 } 2725 2726 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) { 2727 // Arrays are treated like structures. 2728 2729 uint64_t Size = getContext().getTypeSize(Ty); 2730 2731 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 2732 // than eight eightbytes, ..., it has class MEMORY. 2733 if (Size > 512) 2734 return; 2735 2736 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned 2737 // fields, it has class MEMORY. 2738 // 2739 // Only need to check alignment of array base. 2740 if (OffsetBase % getContext().getTypeAlign(AT->getElementType())) 2741 return; 2742 2743 // Otherwise implement simplified merge. We could be smarter about 2744 // this, but it isn't worth it and would be harder to verify. 2745 Current = NoClass; 2746 uint64_t EltSize = getContext().getTypeSize(AT->getElementType()); 2747 uint64_t ArraySize = AT->getSize().getZExtValue(); 2748 2749 // The only case a 256-bit wide vector could be used is when the array 2750 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 2751 // to work for sizes wider than 128, early check and fallback to memory. 2752 // 2753 if (Size > 128 && 2754 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel))) 2755 return; 2756 2757 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) { 2758 Class FieldLo, FieldHi; 2759 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg); 2760 Lo = merge(Lo, FieldLo); 2761 Hi = merge(Hi, FieldHi); 2762 if (Lo == Memory || Hi == Memory) 2763 break; 2764 } 2765 2766 postMerge(Size, Lo, Hi); 2767 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification."); 2768 return; 2769 } 2770 2771 if (const RecordType *RT = Ty->getAs<RecordType>()) { 2772 uint64_t Size = getContext().getTypeSize(Ty); 2773 2774 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger 2775 // than eight eightbytes, ..., it has class MEMORY. 2776 if (Size > 512) 2777 return; 2778 2779 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial 2780 // copy constructor or a non-trivial destructor, it is passed by invisible 2781 // reference. 2782 if (getRecordArgABI(RT, getCXXABI())) 2783 return; 2784 2785 const RecordDecl *RD = RT->getDecl(); 2786 2787 // Assume variable sized types are passed in memory. 2788 if (RD->hasFlexibleArrayMember()) 2789 return; 2790 2791 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 2792 2793 // Reset Lo class, this will be recomputed. 2794 Current = NoClass; 2795 2796 // If this is a C++ record, classify the bases first. 2797 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 2798 for (const auto &I : CXXRD->bases()) { 2799 assert(!I.isVirtual() && !I.getType()->isDependentType() && 2800 "Unexpected base class!"); 2801 const CXXRecordDecl *Base = 2802 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 2803 2804 // Classify this field. 2805 // 2806 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a 2807 // single eightbyte, each is classified separately. Each eightbyte gets 2808 // initialized to class NO_CLASS. 2809 Class FieldLo, FieldHi; 2810 uint64_t Offset = 2811 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base)); 2812 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg); 2813 Lo = merge(Lo, FieldLo); 2814 Hi = merge(Hi, FieldHi); 2815 if (Lo == Memory || Hi == Memory) { 2816 postMerge(Size, Lo, Hi); 2817 return; 2818 } 2819 } 2820 } 2821 2822 // Classify the fields one at a time, merging the results. 2823 unsigned idx = 0; 2824 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 2825 i != e; ++i, ++idx) { 2826 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 2827 bool BitField = i->isBitField(); 2828 2829 // Ignore padding bit-fields. 2830 if (BitField && i->isUnnamedBitfield()) 2831 continue; 2832 2833 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than 2834 // four eightbytes, or it contains unaligned fields, it has class MEMORY. 2835 // 2836 // The only case a 256-bit wide vector could be used is when the struct 2837 // contains a single 256-bit element. Since Lo and Hi logic isn't extended 2838 // to work for sizes wider than 128, early check and fallback to memory. 2839 // 2840 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) || 2841 Size > getNativeVectorSizeForAVXABI(AVXLevel))) { 2842 Lo = Memory; 2843 postMerge(Size, Lo, Hi); 2844 return; 2845 } 2846 // Note, skip this test for bit-fields, see below. 2847 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) { 2848 Lo = Memory; 2849 postMerge(Size, Lo, Hi); 2850 return; 2851 } 2852 2853 // Classify this field. 2854 // 2855 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate 2856 // exceeds a single eightbyte, each is classified 2857 // separately. Each eightbyte gets initialized to class 2858 // NO_CLASS. 2859 Class FieldLo, FieldHi; 2860 2861 // Bit-fields require special handling, they do not force the 2862 // structure to be passed in memory even if unaligned, and 2863 // therefore they can straddle an eightbyte. 2864 if (BitField) { 2865 assert(!i->isUnnamedBitfield()); 2866 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx); 2867 uint64_t Size = i->getBitWidthValue(getContext()); 2868 2869 uint64_t EB_Lo = Offset / 64; 2870 uint64_t EB_Hi = (Offset + Size - 1) / 64; 2871 2872 if (EB_Lo) { 2873 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes."); 2874 FieldLo = NoClass; 2875 FieldHi = Integer; 2876 } else { 2877 FieldLo = Integer; 2878 FieldHi = EB_Hi ? Integer : NoClass; 2879 } 2880 } else 2881 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg); 2882 Lo = merge(Lo, FieldLo); 2883 Hi = merge(Hi, FieldHi); 2884 if (Lo == Memory || Hi == Memory) 2885 break; 2886 } 2887 2888 postMerge(Size, Lo, Hi); 2889 } 2890 } 2891 2892 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const { 2893 // If this is a scalar LLVM value then assume LLVM will pass it in the right 2894 // place naturally. 2895 if (!isAggregateTypeForABI(Ty)) { 2896 // Treat an enum type as its underlying type. 2897 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2898 Ty = EnumTy->getDecl()->getIntegerType(); 2899 2900 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 2901 : ABIArgInfo::getDirect()); 2902 } 2903 2904 return getNaturalAlignIndirect(Ty); 2905 } 2906 2907 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const { 2908 if (const VectorType *VecTy = Ty->getAs<VectorType>()) { 2909 uint64_t Size = getContext().getTypeSize(VecTy); 2910 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel); 2911 if (Size <= 64 || Size > LargestVector) 2912 return true; 2913 } 2914 2915 return false; 2916 } 2917 2918 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty, 2919 unsigned freeIntRegs) const { 2920 // If this is a scalar LLVM value then assume LLVM will pass it in the right 2921 // place naturally. 2922 // 2923 // This assumption is optimistic, as there could be free registers available 2924 // when we need to pass this argument in memory, and LLVM could try to pass 2925 // the argument in the free register. This does not seem to happen currently, 2926 // but this code would be much safer if we could mark the argument with 2927 // 'onstack'. See PR12193. 2928 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) { 2929 // Treat an enum type as its underlying type. 2930 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 2931 Ty = EnumTy->getDecl()->getIntegerType(); 2932 2933 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 2934 : ABIArgInfo::getDirect()); 2935 } 2936 2937 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 2938 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 2939 2940 // Compute the byval alignment. We specify the alignment of the byval in all 2941 // cases so that the mid-level optimizer knows the alignment of the byval. 2942 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U); 2943 2944 // Attempt to avoid passing indirect results using byval when possible. This 2945 // is important for good codegen. 2946 // 2947 // We do this by coercing the value into a scalar type which the backend can 2948 // handle naturally (i.e., without using byval). 2949 // 2950 // For simplicity, we currently only do this when we have exhausted all of the 2951 // free integer registers. Doing this when there are free integer registers 2952 // would require more care, as we would have to ensure that the coerced value 2953 // did not claim the unused register. That would require either reording the 2954 // arguments to the function (so that any subsequent inreg values came first), 2955 // or only doing this optimization when there were no following arguments that 2956 // might be inreg. 2957 // 2958 // We currently expect it to be rare (particularly in well written code) for 2959 // arguments to be passed on the stack when there are still free integer 2960 // registers available (this would typically imply large structs being passed 2961 // by value), so this seems like a fair tradeoff for now. 2962 // 2963 // We can revisit this if the backend grows support for 'onstack' parameter 2964 // attributes. See PR12193. 2965 if (freeIntRegs == 0) { 2966 uint64_t Size = getContext().getTypeSize(Ty); 2967 2968 // If this type fits in an eightbyte, coerce it into the matching integral 2969 // type, which will end up on the stack (with alignment 8). 2970 if (Align == 8 && Size <= 64) 2971 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 2972 Size)); 2973 } 2974 2975 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align)); 2976 } 2977 2978 /// The ABI specifies that a value should be passed in a full vector XMM/YMM 2979 /// register. Pick an LLVM IR type that will be passed as a vector register. 2980 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const { 2981 // Wrapper structs/arrays that only contain vectors are passed just like 2982 // vectors; strip them off if present. 2983 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext())) 2984 Ty = QualType(InnerTy, 0); 2985 2986 llvm::Type *IRType = CGT.ConvertType(Ty); 2987 if (isa<llvm::VectorType>(IRType) || 2988 IRType->getTypeID() == llvm::Type::FP128TyID) 2989 return IRType; 2990 2991 // We couldn't find the preferred IR vector type for 'Ty'. 2992 uint64_t Size = getContext().getTypeSize(Ty); 2993 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!"); 2994 2995 // Return a LLVM IR vector type based on the size of 'Ty'. 2996 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()), 2997 Size / 64); 2998 } 2999 3000 /// BitsContainNoUserData - Return true if the specified [start,end) bit range 3001 /// is known to either be off the end of the specified type or being in 3002 /// alignment padding. The user type specified is known to be at most 128 bits 3003 /// in size, and have passed through X86_64ABIInfo::classify with a successful 3004 /// classification that put one of the two halves in the INTEGER class. 3005 /// 3006 /// It is conservatively correct to return false. 3007 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit, 3008 unsigned EndBit, ASTContext &Context) { 3009 // If the bytes being queried are off the end of the type, there is no user 3010 // data hiding here. This handles analysis of builtins, vectors and other 3011 // types that don't contain interesting padding. 3012 unsigned TySize = (unsigned)Context.getTypeSize(Ty); 3013 if (TySize <= StartBit) 3014 return true; 3015 3016 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 3017 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType()); 3018 unsigned NumElts = (unsigned)AT->getSize().getZExtValue(); 3019 3020 // Check each element to see if the element overlaps with the queried range. 3021 for (unsigned i = 0; i != NumElts; ++i) { 3022 // If the element is after the span we care about, then we're done.. 3023 unsigned EltOffset = i*EltSize; 3024 if (EltOffset >= EndBit) break; 3025 3026 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0; 3027 if (!BitsContainNoUserData(AT->getElementType(), EltStart, 3028 EndBit-EltOffset, Context)) 3029 return false; 3030 } 3031 // If it overlaps no elements, then it is safe to process as padding. 3032 return true; 3033 } 3034 3035 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3036 const RecordDecl *RD = RT->getDecl(); 3037 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 3038 3039 // If this is a C++ record, check the bases first. 3040 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 3041 for (const auto &I : CXXRD->bases()) { 3042 assert(!I.isVirtual() && !I.getType()->isDependentType() && 3043 "Unexpected base class!"); 3044 const CXXRecordDecl *Base = 3045 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 3046 3047 // If the base is after the span we care about, ignore it. 3048 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base)); 3049 if (BaseOffset >= EndBit) continue; 3050 3051 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0; 3052 if (!BitsContainNoUserData(I.getType(), BaseStart, 3053 EndBit-BaseOffset, Context)) 3054 return false; 3055 } 3056 } 3057 3058 // Verify that no field has data that overlaps the region of interest. Yes 3059 // this could be sped up a lot by being smarter about queried fields, 3060 // however we're only looking at structs up to 16 bytes, so we don't care 3061 // much. 3062 unsigned idx = 0; 3063 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 3064 i != e; ++i, ++idx) { 3065 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx); 3066 3067 // If we found a field after the region we care about, then we're done. 3068 if (FieldOffset >= EndBit) break; 3069 3070 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0; 3071 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset, 3072 Context)) 3073 return false; 3074 } 3075 3076 // If nothing in this record overlapped the area of interest, then we're 3077 // clean. 3078 return true; 3079 } 3080 3081 return false; 3082 } 3083 3084 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a 3085 /// float member at the specified offset. For example, {int,{float}} has a 3086 /// float at offset 4. It is conservatively correct for this routine to return 3087 /// false. 3088 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset, 3089 const llvm::DataLayout &TD) { 3090 // Base case if we find a float. 3091 if (IROffset == 0 && IRType->isFloatTy()) 3092 return true; 3093 3094 // If this is a struct, recurse into the field at the specified offset. 3095 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3096 const llvm::StructLayout *SL = TD.getStructLayout(STy); 3097 unsigned Elt = SL->getElementContainingOffset(IROffset); 3098 IROffset -= SL->getElementOffset(Elt); 3099 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD); 3100 } 3101 3102 // If this is an array, recurse into the field at the specified offset. 3103 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3104 llvm::Type *EltTy = ATy->getElementType(); 3105 unsigned EltSize = TD.getTypeAllocSize(EltTy); 3106 IROffset -= IROffset/EltSize*EltSize; 3107 return ContainsFloatAtOffset(EltTy, IROffset, TD); 3108 } 3109 3110 return false; 3111 } 3112 3113 3114 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the 3115 /// low 8 bytes of an XMM register, corresponding to the SSE class. 3116 llvm::Type *X86_64ABIInfo:: 3117 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3118 QualType SourceTy, unsigned SourceOffset) const { 3119 // The only three choices we have are either double, <2 x float>, or float. We 3120 // pass as float if the last 4 bytes is just padding. This happens for 3121 // structs that contain 3 floats. 3122 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32, 3123 SourceOffset*8+64, getContext())) 3124 return llvm::Type::getFloatTy(getVMContext()); 3125 3126 // We want to pass as <2 x float> if the LLVM IR type contains a float at 3127 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the 3128 // case. 3129 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) && 3130 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout())) 3131 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2); 3132 3133 return llvm::Type::getDoubleTy(getVMContext()); 3134 } 3135 3136 3137 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in 3138 /// an 8-byte GPR. This means that we either have a scalar or we are talking 3139 /// about the high or low part of an up-to-16-byte struct. This routine picks 3140 /// the best LLVM IR type to represent this, which may be i64 or may be anything 3141 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*, 3142 /// etc). 3143 /// 3144 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for 3145 /// the source type. IROffset is an offset in bytes into the LLVM IR type that 3146 /// the 8-byte value references. PrefType may be null. 3147 /// 3148 /// SourceTy is the source-level type for the entire argument. SourceOffset is 3149 /// an offset into this that we're processing (which is always either 0 or 8). 3150 /// 3151 llvm::Type *X86_64ABIInfo:: 3152 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset, 3153 QualType SourceTy, unsigned SourceOffset) const { 3154 // If we're dealing with an un-offset LLVM IR type, then it means that we're 3155 // returning an 8-byte unit starting with it. See if we can safely use it. 3156 if (IROffset == 0) { 3157 // Pointers and int64's always fill the 8-byte unit. 3158 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) || 3159 IRType->isIntegerTy(64)) 3160 return IRType; 3161 3162 // If we have a 1/2/4-byte integer, we can use it only if the rest of the 3163 // goodness in the source type is just tail padding. This is allowed to 3164 // kick in for struct {double,int} on the int, but not on 3165 // struct{double,int,int} because we wouldn't return the second int. We 3166 // have to do this analysis on the source type because we can't depend on 3167 // unions being lowered a specific way etc. 3168 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) || 3169 IRType->isIntegerTy(32) || 3170 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) { 3171 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 : 3172 cast<llvm::IntegerType>(IRType)->getBitWidth(); 3173 3174 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth, 3175 SourceOffset*8+64, getContext())) 3176 return IRType; 3177 } 3178 } 3179 3180 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) { 3181 // If this is a struct, recurse into the field at the specified offset. 3182 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy); 3183 if (IROffset < SL->getSizeInBytes()) { 3184 unsigned FieldIdx = SL->getElementContainingOffset(IROffset); 3185 IROffset -= SL->getElementOffset(FieldIdx); 3186 3187 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset, 3188 SourceTy, SourceOffset); 3189 } 3190 } 3191 3192 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) { 3193 llvm::Type *EltTy = ATy->getElementType(); 3194 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy); 3195 unsigned EltOffset = IROffset/EltSize*EltSize; 3196 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy, 3197 SourceOffset); 3198 } 3199 3200 // Okay, we don't have any better idea of what to pass, so we pass this in an 3201 // integer register that isn't too big to fit the rest of the struct. 3202 unsigned TySizeInBytes = 3203 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity(); 3204 3205 assert(TySizeInBytes != SourceOffset && "Empty field?"); 3206 3207 // It is always safe to classify this as an integer type up to i64 that 3208 // isn't larger than the structure. 3209 return llvm::IntegerType::get(getVMContext(), 3210 std::min(TySizeInBytes-SourceOffset, 8U)*8); 3211 } 3212 3213 3214 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally 3215 /// be used as elements of a two register pair to pass or return, return a 3216 /// first class aggregate to represent them. For example, if the low part of 3217 /// a by-value argument should be passed as i32* and the high part as float, 3218 /// return {i32*, float}. 3219 static llvm::Type * 3220 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi, 3221 const llvm::DataLayout &TD) { 3222 // In order to correctly satisfy the ABI, we need to the high part to start 3223 // at offset 8. If the high and low parts we inferred are both 4-byte types 3224 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have 3225 // the second element at offset 8. Check for this: 3226 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo); 3227 unsigned HiAlign = TD.getABITypeAlignment(Hi); 3228 unsigned HiStart = llvm::alignTo(LoSize, HiAlign); 3229 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!"); 3230 3231 // To handle this, we have to increase the size of the low part so that the 3232 // second element will start at an 8 byte offset. We can't increase the size 3233 // of the second element because it might make us access off the end of the 3234 // struct. 3235 if (HiStart != 8) { 3236 // There are usually two sorts of types the ABI generation code can produce 3237 // for the low part of a pair that aren't 8 bytes in size: float or 3238 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and 3239 // NaCl). 3240 // Promote these to a larger type. 3241 if (Lo->isFloatTy()) 3242 Lo = llvm::Type::getDoubleTy(Lo->getContext()); 3243 else { 3244 assert((Lo->isIntegerTy() || Lo->isPointerTy()) 3245 && "Invalid/unknown lo type"); 3246 Lo = llvm::Type::getInt64Ty(Lo->getContext()); 3247 } 3248 } 3249 3250 llvm::StructType *Result = llvm::StructType::get(Lo, Hi); 3251 3252 // Verify that the second element is at an 8-byte offset. 3253 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 && 3254 "Invalid x86-64 argument pair!"); 3255 return Result; 3256 } 3257 3258 ABIArgInfo X86_64ABIInfo:: 3259 classifyReturnType(QualType RetTy) const { 3260 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the 3261 // classification algorithm. 3262 X86_64ABIInfo::Class Lo, Hi; 3263 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true); 3264 3265 // Check some invariants. 3266 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3267 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3268 3269 llvm::Type *ResType = nullptr; 3270 switch (Lo) { 3271 case NoClass: 3272 if (Hi == NoClass) 3273 return ABIArgInfo::getIgnore(); 3274 // If the low part is just padding, it takes no register, leave ResType 3275 // null. 3276 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3277 "Unknown missing lo part"); 3278 break; 3279 3280 case SSEUp: 3281 case X87Up: 3282 llvm_unreachable("Invalid classification for lo word."); 3283 3284 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via 3285 // hidden argument. 3286 case Memory: 3287 return getIndirectReturnResult(RetTy); 3288 3289 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next 3290 // available register of the sequence %rax, %rdx is used. 3291 case Integer: 3292 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3293 3294 // If we have a sign or zero extended integer, make sure to return Extend 3295 // so that the parameter gets the right LLVM IR attributes. 3296 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3297 // Treat an enum type as its underlying type. 3298 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 3299 RetTy = EnumTy->getDecl()->getIntegerType(); 3300 3301 if (RetTy->isIntegralOrEnumerationType() && 3302 RetTy->isPromotableIntegerType()) 3303 return ABIArgInfo::getExtend(RetTy); 3304 } 3305 break; 3306 3307 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next 3308 // available SSE register of the sequence %xmm0, %xmm1 is used. 3309 case SSE: 3310 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0); 3311 break; 3312 3313 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is 3314 // returned on the X87 stack in %st0 as 80-bit x87 number. 3315 case X87: 3316 ResType = llvm::Type::getX86_FP80Ty(getVMContext()); 3317 break; 3318 3319 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real 3320 // part of the value is returned in %st0 and the imaginary part in 3321 // %st1. 3322 case ComplexX87: 3323 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification."); 3324 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()), 3325 llvm::Type::getX86_FP80Ty(getVMContext())); 3326 break; 3327 } 3328 3329 llvm::Type *HighPart = nullptr; 3330 switch (Hi) { 3331 // Memory was handled previously and X87 should 3332 // never occur as a hi class. 3333 case Memory: 3334 case X87: 3335 llvm_unreachable("Invalid classification for hi word."); 3336 3337 case ComplexX87: // Previously handled. 3338 case NoClass: 3339 break; 3340 3341 case Integer: 3342 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3343 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3344 return ABIArgInfo::getDirect(HighPart, 8); 3345 break; 3346 case SSE: 3347 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3348 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3349 return ABIArgInfo::getDirect(HighPart, 8); 3350 break; 3351 3352 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte 3353 // is passed in the next available eightbyte chunk if the last used 3354 // vector register. 3355 // 3356 // SSEUP should always be preceded by SSE, just widen. 3357 case SSEUp: 3358 assert(Lo == SSE && "Unexpected SSEUp classification."); 3359 ResType = GetByteVectorType(RetTy); 3360 break; 3361 3362 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is 3363 // returned together with the previous X87 value in %st0. 3364 case X87Up: 3365 // If X87Up is preceded by X87, we don't need to do 3366 // anything. However, in some cases with unions it may not be 3367 // preceded by X87. In such situations we follow gcc and pass the 3368 // extra bits in an SSE reg. 3369 if (Lo != X87) { 3370 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8); 3371 if (Lo == NoClass) // Return HighPart at offset 8 in memory. 3372 return ABIArgInfo::getDirect(HighPart, 8); 3373 } 3374 break; 3375 } 3376 3377 // If a high part was specified, merge it together with the low part. It is 3378 // known to pass in the high eightbyte of the result. We do this by forming a 3379 // first class struct aggregate with the high and low part: {low, high} 3380 if (HighPart) 3381 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3382 3383 return ABIArgInfo::getDirect(ResType); 3384 } 3385 3386 ABIArgInfo X86_64ABIInfo::classifyArgumentType( 3387 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE, 3388 bool isNamedArg) 3389 const 3390 { 3391 Ty = useFirstFieldIfTransparentUnion(Ty); 3392 3393 X86_64ABIInfo::Class Lo, Hi; 3394 classify(Ty, 0, Lo, Hi, isNamedArg); 3395 3396 // Check some invariants. 3397 // FIXME: Enforce these by construction. 3398 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification."); 3399 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification."); 3400 3401 neededInt = 0; 3402 neededSSE = 0; 3403 llvm::Type *ResType = nullptr; 3404 switch (Lo) { 3405 case NoClass: 3406 if (Hi == NoClass) 3407 return ABIArgInfo::getIgnore(); 3408 // If the low part is just padding, it takes no register, leave ResType 3409 // null. 3410 assert((Hi == SSE || Hi == Integer || Hi == X87Up) && 3411 "Unknown missing lo part"); 3412 break; 3413 3414 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument 3415 // on the stack. 3416 case Memory: 3417 3418 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or 3419 // COMPLEX_X87, it is passed in memory. 3420 case X87: 3421 case ComplexX87: 3422 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect) 3423 ++neededInt; 3424 return getIndirectResult(Ty, freeIntRegs); 3425 3426 case SSEUp: 3427 case X87Up: 3428 llvm_unreachable("Invalid classification for lo word."); 3429 3430 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next 3431 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 3432 // and %r9 is used. 3433 case Integer: 3434 ++neededInt; 3435 3436 // Pick an 8-byte type based on the preferred type. 3437 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0); 3438 3439 // If we have a sign or zero extended integer, make sure to return Extend 3440 // so that the parameter gets the right LLVM IR attributes. 3441 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) { 3442 // Treat an enum type as its underlying type. 3443 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3444 Ty = EnumTy->getDecl()->getIntegerType(); 3445 3446 if (Ty->isIntegralOrEnumerationType() && 3447 Ty->isPromotableIntegerType()) 3448 return ABIArgInfo::getExtend(Ty); 3449 } 3450 3451 break; 3452 3453 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next 3454 // available SSE register is used, the registers are taken in the 3455 // order from %xmm0 to %xmm7. 3456 case SSE: { 3457 llvm::Type *IRType = CGT.ConvertType(Ty); 3458 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0); 3459 ++neededSSE; 3460 break; 3461 } 3462 } 3463 3464 llvm::Type *HighPart = nullptr; 3465 switch (Hi) { 3466 // Memory was handled previously, ComplexX87 and X87 should 3467 // never occur as hi classes, and X87Up must be preceded by X87, 3468 // which is passed in memory. 3469 case Memory: 3470 case X87: 3471 case ComplexX87: 3472 llvm_unreachable("Invalid classification for hi word."); 3473 3474 case NoClass: break; 3475 3476 case Integer: 3477 ++neededInt; 3478 // Pick an 8-byte type based on the preferred type. 3479 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3480 3481 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3482 return ABIArgInfo::getDirect(HighPart, 8); 3483 break; 3484 3485 // X87Up generally doesn't occur here (long double is passed in 3486 // memory), except in situations involving unions. 3487 case X87Up: 3488 case SSE: 3489 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8); 3490 3491 if (Lo == NoClass) // Pass HighPart at offset 8 in memory. 3492 return ABIArgInfo::getDirect(HighPart, 8); 3493 3494 ++neededSSE; 3495 break; 3496 3497 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the 3498 // eightbyte is passed in the upper half of the last used SSE 3499 // register. This only happens when 128-bit vectors are passed. 3500 case SSEUp: 3501 assert(Lo == SSE && "Unexpected SSEUp classification"); 3502 ResType = GetByteVectorType(Ty); 3503 break; 3504 } 3505 3506 // If a high part was specified, merge it together with the low part. It is 3507 // known to pass in the high eightbyte of the result. We do this by forming a 3508 // first class struct aggregate with the high and low part: {low, high} 3509 if (HighPart) 3510 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout()); 3511 3512 return ABIArgInfo::getDirect(ResType); 3513 } 3514 3515 ABIArgInfo 3516 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt, 3517 unsigned &NeededSSE) const { 3518 auto RT = Ty->getAs<RecordType>(); 3519 assert(RT && "classifyRegCallStructType only valid with struct types"); 3520 3521 if (RT->getDecl()->hasFlexibleArrayMember()) 3522 return getIndirectReturnResult(Ty); 3523 3524 // Sum up bases 3525 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 3526 if (CXXRD->isDynamicClass()) { 3527 NeededInt = NeededSSE = 0; 3528 return getIndirectReturnResult(Ty); 3529 } 3530 3531 for (const auto &I : CXXRD->bases()) 3532 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE) 3533 .isIndirect()) { 3534 NeededInt = NeededSSE = 0; 3535 return getIndirectReturnResult(Ty); 3536 } 3537 } 3538 3539 // Sum up members 3540 for (const auto *FD : RT->getDecl()->fields()) { 3541 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) { 3542 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE) 3543 .isIndirect()) { 3544 NeededInt = NeededSSE = 0; 3545 return getIndirectReturnResult(Ty); 3546 } 3547 } else { 3548 unsigned LocalNeededInt, LocalNeededSSE; 3549 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt, 3550 LocalNeededSSE, true) 3551 .isIndirect()) { 3552 NeededInt = NeededSSE = 0; 3553 return getIndirectReturnResult(Ty); 3554 } 3555 NeededInt += LocalNeededInt; 3556 NeededSSE += LocalNeededSSE; 3557 } 3558 } 3559 3560 return ABIArgInfo::getDirect(); 3561 } 3562 3563 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty, 3564 unsigned &NeededInt, 3565 unsigned &NeededSSE) const { 3566 3567 NeededInt = 0; 3568 NeededSSE = 0; 3569 3570 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE); 3571 } 3572 3573 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 3574 3575 const unsigned CallingConv = FI.getCallingConvention(); 3576 // It is possible to force Win64 calling convention on any x86_64 target by 3577 // using __attribute__((ms_abi)). In such case to correctly emit Win64 3578 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo. 3579 if (CallingConv == llvm::CallingConv::Win64) { 3580 WinX86_64ABIInfo Win64ABIInfo(CGT); 3581 Win64ABIInfo.computeInfo(FI); 3582 return; 3583 } 3584 3585 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall; 3586 3587 // Keep track of the number of assigned registers. 3588 unsigned FreeIntRegs = IsRegCall ? 11 : 6; 3589 unsigned FreeSSERegs = IsRegCall ? 16 : 8; 3590 unsigned NeededInt, NeededSSE; 3591 3592 if (!::classifyReturnType(getCXXABI(), FI, *this)) { 3593 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() && 3594 !FI.getReturnType()->getTypePtr()->isUnionType()) { 3595 FI.getReturnInfo() = 3596 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE); 3597 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3598 FreeIntRegs -= NeededInt; 3599 FreeSSERegs -= NeededSSE; 3600 } else { 3601 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3602 } 3603 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) { 3604 // Complex Long Double Type is passed in Memory when Regcall 3605 // calling convention is used. 3606 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>(); 3607 if (getContext().getCanonicalType(CT->getElementType()) == 3608 getContext().LongDoubleTy) 3609 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType()); 3610 } else 3611 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 3612 } 3613 3614 // If the return value is indirect, then the hidden argument is consuming one 3615 // integer register. 3616 if (FI.getReturnInfo().isIndirect()) 3617 --FreeIntRegs; 3618 3619 // The chain argument effectively gives us another free register. 3620 if (FI.isChainCall()) 3621 ++FreeIntRegs; 3622 3623 unsigned NumRequiredArgs = FI.getNumRequiredArgs(); 3624 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers 3625 // get assigned (in left-to-right order) for passing as follows... 3626 unsigned ArgNo = 0; 3627 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end(); 3628 it != ie; ++it, ++ArgNo) { 3629 bool IsNamedArg = ArgNo < NumRequiredArgs; 3630 3631 if (IsRegCall && it->type->isStructureOrClassType()) 3632 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE); 3633 else 3634 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt, 3635 NeededSSE, IsNamedArg); 3636 3637 // AMD64-ABI 3.2.3p3: If there are no registers available for any 3638 // eightbyte of an argument, the whole argument is passed on the 3639 // stack. If registers have already been assigned for some 3640 // eightbytes of such an argument, the assignments get reverted. 3641 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) { 3642 FreeIntRegs -= NeededInt; 3643 FreeSSERegs -= NeededSSE; 3644 } else { 3645 it->info = getIndirectResult(it->type, FreeIntRegs); 3646 } 3647 } 3648 } 3649 3650 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF, 3651 Address VAListAddr, QualType Ty) { 3652 Address overflow_arg_area_p = 3653 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p"); 3654 llvm::Value *overflow_arg_area = 3655 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area"); 3656 3657 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16 3658 // byte boundary if alignment needed by type exceeds 8 byte boundary. 3659 // It isn't stated explicitly in the standard, but in practice we use 3660 // alignment greater than 16 where necessary. 3661 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty); 3662 if (Align > CharUnits::fromQuantity(8)) { 3663 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area, 3664 Align); 3665 } 3666 3667 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area. 3668 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 3669 llvm::Value *Res = 3670 CGF.Builder.CreateBitCast(overflow_arg_area, 3671 llvm::PointerType::getUnqual(LTy)); 3672 3673 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to: 3674 // l->overflow_arg_area + sizeof(type). 3675 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to 3676 // an 8 byte boundary. 3677 3678 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8; 3679 llvm::Value *Offset = 3680 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7); 3681 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset, 3682 "overflow_arg_area.next"); 3683 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p); 3684 3685 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type. 3686 return Address(Res, Align); 3687 } 3688 3689 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 3690 QualType Ty) const { 3691 // Assume that va_list type is correct; should be pointer to LLVM type: 3692 // struct { 3693 // i32 gp_offset; 3694 // i32 fp_offset; 3695 // i8* overflow_arg_area; 3696 // i8* reg_save_area; 3697 // }; 3698 unsigned neededInt, neededSSE; 3699 3700 Ty = getContext().getCanonicalType(Ty); 3701 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE, 3702 /*isNamedArg*/false); 3703 3704 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed 3705 // in the registers. If not go to step 7. 3706 if (!neededInt && !neededSSE) 3707 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 3708 3709 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of 3710 // general purpose registers needed to pass type and num_fp to hold 3711 // the number of floating point registers needed. 3712 3713 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into 3714 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or 3715 // l->fp_offset > 304 - num_fp * 16 go to step 7. 3716 // 3717 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of 3718 // register save space). 3719 3720 llvm::Value *InRegs = nullptr; 3721 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid(); 3722 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr; 3723 if (neededInt) { 3724 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p"); 3725 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset"); 3726 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8); 3727 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp"); 3728 } 3729 3730 if (neededSSE) { 3731 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p"); 3732 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset"); 3733 llvm::Value *FitsInFP = 3734 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16); 3735 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp"); 3736 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP; 3737 } 3738 3739 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 3740 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 3741 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 3742 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 3743 3744 // Emit code to load the value if it was passed in registers. 3745 3746 CGF.EmitBlock(InRegBlock); 3747 3748 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with 3749 // an offset of l->gp_offset and/or l->fp_offset. This may require 3750 // copying to a temporary location in case the parameter is passed 3751 // in different register classes or requires an alignment greater 3752 // than 8 for general purpose registers and 16 for XMM registers. 3753 // 3754 // FIXME: This really results in shameful code when we end up needing to 3755 // collect arguments from different places; often what should result in a 3756 // simple assembling of a structure from scattered addresses has many more 3757 // loads than necessary. Can we clean this up? 3758 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty); 3759 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad( 3760 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area"); 3761 3762 Address RegAddr = Address::invalid(); 3763 if (neededInt && neededSSE) { 3764 // FIXME: Cleanup. 3765 assert(AI.isDirect() && "Unexpected ABI info for mixed regs"); 3766 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType()); 3767 Address Tmp = CGF.CreateMemTemp(Ty); 3768 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 3769 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs"); 3770 llvm::Type *TyLo = ST->getElementType(0); 3771 llvm::Type *TyHi = ST->getElementType(1); 3772 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) && 3773 "Unexpected ABI info for mixed regs"); 3774 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo); 3775 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi); 3776 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset); 3777 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset); 3778 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr; 3779 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr; 3780 3781 // Copy the first element. 3782 // FIXME: Our choice of alignment here and below is probably pessimistic. 3783 llvm::Value *V = CGF.Builder.CreateAlignedLoad( 3784 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo), 3785 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo))); 3786 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 3787 3788 // Copy the second element. 3789 V = CGF.Builder.CreateAlignedLoad( 3790 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi), 3791 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi))); 3792 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 3793 3794 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 3795 } else if (neededInt) { 3796 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset), 3797 CharUnits::fromQuantity(8)); 3798 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 3799 3800 // Copy to a temporary if necessary to ensure the appropriate alignment. 3801 std::pair<CharUnits, CharUnits> SizeAlign = 3802 getContext().getTypeInfoInChars(Ty); 3803 uint64_t TySize = SizeAlign.first.getQuantity(); 3804 CharUnits TyAlign = SizeAlign.second; 3805 3806 // Copy into a temporary if the type is more aligned than the 3807 // register save area. 3808 if (TyAlign.getQuantity() > 8) { 3809 Address Tmp = CGF.CreateMemTemp(Ty); 3810 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false); 3811 RegAddr = Tmp; 3812 } 3813 3814 } else if (neededSSE == 1) { 3815 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), 3816 CharUnits::fromQuantity(16)); 3817 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy); 3818 } else { 3819 assert(neededSSE == 2 && "Invalid number of needed registers!"); 3820 // SSE registers are spaced 16 bytes apart in the register save 3821 // area, we need to collect the two eightbytes together. 3822 // The ABI isn't explicit about this, but it seems reasonable 3823 // to assume that the slots are 16-byte aligned, since the stack is 3824 // naturally 16-byte aligned and the prologue is expected to store 3825 // all the SSE registers to the RSA. 3826 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset), 3827 CharUnits::fromQuantity(16)); 3828 Address RegAddrHi = 3829 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo, 3830 CharUnits::fromQuantity(16)); 3831 llvm::Type *ST = AI.canHaveCoerceToType() 3832 ? AI.getCoerceToType() 3833 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy); 3834 llvm::Value *V; 3835 Address Tmp = CGF.CreateMemTemp(Ty); 3836 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST); 3837 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 3838 RegAddrLo, ST->getStructElementType(0))); 3839 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0)); 3840 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast( 3841 RegAddrHi, ST->getStructElementType(1))); 3842 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1)); 3843 3844 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy); 3845 } 3846 3847 // AMD64-ABI 3.5.7p5: Step 5. Set: 3848 // l->gp_offset = l->gp_offset + num_gp * 8 3849 // l->fp_offset = l->fp_offset + num_fp * 16. 3850 if (neededInt) { 3851 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8); 3852 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset), 3853 gp_offset_p); 3854 } 3855 if (neededSSE) { 3856 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16); 3857 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset), 3858 fp_offset_p); 3859 } 3860 CGF.EmitBranch(ContBlock); 3861 3862 // Emit code to load the value if it was passed in memory. 3863 3864 CGF.EmitBlock(InMemBlock); 3865 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty); 3866 3867 // Return the appropriate result. 3868 3869 CGF.EmitBlock(ContBlock); 3870 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock, 3871 "vaarg.addr"); 3872 return ResAddr; 3873 } 3874 3875 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr, 3876 QualType Ty) const { 3877 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 3878 CGF.getContext().getTypeInfoInChars(Ty), 3879 CharUnits::fromQuantity(8), 3880 /*allowHigherAlign*/ false); 3881 } 3882 3883 ABIArgInfo 3884 WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs, 3885 const ABIArgInfo ¤t) const { 3886 // Assumes vectorCall calling convention. 3887 const Type *Base = nullptr; 3888 uint64_t NumElts = 0; 3889 3890 if (!Ty->isBuiltinType() && !Ty->isVectorType() && 3891 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) { 3892 FreeSSERegs -= NumElts; 3893 return getDirectX86Hva(); 3894 } 3895 return current; 3896 } 3897 3898 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs, 3899 bool IsReturnType, bool IsVectorCall, 3900 bool IsRegCall) const { 3901 3902 if (Ty->isVoidType()) 3903 return ABIArgInfo::getIgnore(); 3904 3905 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 3906 Ty = EnumTy->getDecl()->getIntegerType(); 3907 3908 TypeInfo Info = getContext().getTypeInfo(Ty); 3909 uint64_t Width = Info.Width; 3910 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align); 3911 3912 const RecordType *RT = Ty->getAs<RecordType>(); 3913 if (RT) { 3914 if (!IsReturnType) { 3915 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI())) 3916 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 3917 } 3918 3919 if (RT->getDecl()->hasFlexibleArrayMember()) 3920 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 3921 3922 } 3923 3924 const Type *Base = nullptr; 3925 uint64_t NumElts = 0; 3926 // vectorcall adds the concept of a homogenous vector aggregate, similar to 3927 // other targets. 3928 if ((IsVectorCall || IsRegCall) && 3929 isHomogeneousAggregate(Ty, Base, NumElts)) { 3930 if (IsRegCall) { 3931 if (FreeSSERegs >= NumElts) { 3932 FreeSSERegs -= NumElts; 3933 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType()) 3934 return ABIArgInfo::getDirect(); 3935 return ABIArgInfo::getExpand(); 3936 } 3937 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 3938 } else if (IsVectorCall) { 3939 if (FreeSSERegs >= NumElts && 3940 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) { 3941 FreeSSERegs -= NumElts; 3942 return ABIArgInfo::getDirect(); 3943 } else if (IsReturnType) { 3944 return ABIArgInfo::getExpand(); 3945 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) { 3946 // HVAs are delayed and reclassified in the 2nd step. 3947 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 3948 } 3949 } 3950 } 3951 3952 if (Ty->isMemberPointerType()) { 3953 // If the member pointer is represented by an LLVM int or ptr, pass it 3954 // directly. 3955 llvm::Type *LLTy = CGT.ConvertType(Ty); 3956 if (LLTy->isPointerTy() || LLTy->isIntegerTy()) 3957 return ABIArgInfo::getDirect(); 3958 } 3959 3960 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) { 3961 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is 3962 // not 1, 2, 4, or 8 bytes, must be passed by reference." 3963 if (Width > 64 || !llvm::isPowerOf2_64(Width)) 3964 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 3965 3966 // Otherwise, coerce it to a small integer. 3967 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width)); 3968 } 3969 3970 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) { 3971 switch (BT->getKind()) { 3972 case BuiltinType::Bool: 3973 // Bool type is always extended to the ABI, other builtin types are not 3974 // extended. 3975 return ABIArgInfo::getExtend(Ty); 3976 3977 case BuiltinType::LongDouble: 3978 // Mingw64 GCC uses the old 80 bit extended precision floating point 3979 // unit. It passes them indirectly through memory. 3980 if (IsMingw64) { 3981 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat(); 3982 if (LDF == &llvm::APFloat::x87DoubleExtended()) 3983 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 3984 } 3985 break; 3986 3987 case BuiltinType::Int128: 3988 case BuiltinType::UInt128: 3989 // If it's a parameter type, the normal ABI rule is that arguments larger 3990 // than 8 bytes are passed indirectly. GCC follows it. We follow it too, 3991 // even though it isn't particularly efficient. 3992 if (!IsReturnType) 3993 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false); 3994 3995 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that. 3996 // Clang matches them for compatibility. 3997 return ABIArgInfo::getDirect( 3998 llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()), 2)); 3999 4000 default: 4001 break; 4002 } 4003 } 4004 4005 return ABIArgInfo::getDirect(); 4006 } 4007 4008 void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, 4009 unsigned FreeSSERegs, 4010 bool IsVectorCall, 4011 bool IsRegCall) const { 4012 unsigned Count = 0; 4013 for (auto &I : FI.arguments()) { 4014 // Vectorcall in x64 only permits the first 6 arguments to be passed 4015 // as XMM/YMM registers. 4016 if (Count < VectorcallMaxParamNumAsReg) 4017 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall); 4018 else { 4019 // Since these cannot be passed in registers, pretend no registers 4020 // are left. 4021 unsigned ZeroSSERegsAvail = 0; 4022 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false, 4023 IsVectorCall, IsRegCall); 4024 } 4025 ++Count; 4026 } 4027 4028 for (auto &I : FI.arguments()) { 4029 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info); 4030 } 4031 } 4032 4033 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const { 4034 bool IsVectorCall = 4035 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall; 4036 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall; 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() && T->isFloat128Type()) 6334 return true; 6335 if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() && 6336 Context.getTypeSize(T) > 64) 6337 return true; 6338 if (const auto *AT = T->getAsArrayTypeUnsafe()) 6339 return isUnsupportedType(Context, AT->getElementType()); 6340 const auto *RT = T->getAs<RecordType>(); 6341 if (!RT) 6342 return false; 6343 const RecordDecl *RD = RT->getDecl(); 6344 6345 // If this is a C++ record, check the bases first. 6346 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6347 for (const CXXBaseSpecifier &I : CXXRD->bases()) 6348 if (isUnsupportedType(Context, I.getType())) 6349 return true; 6350 6351 for (const FieldDecl *I : RD->fields()) 6352 if (isUnsupportedType(Context, I->getType())) 6353 return true; 6354 return false; 6355 } 6356 6357 /// Coerce the given type into an array with maximum allowed size of elements. 6358 static ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, ASTContext &Context, 6359 llvm::LLVMContext &LLVMContext, 6360 unsigned MaxSize) { 6361 // Alignment and Size are measured in bits. 6362 const uint64_t Size = Context.getTypeSize(Ty); 6363 const uint64_t Alignment = Context.getTypeAlign(Ty); 6364 const unsigned Div = std::min<unsigned>(MaxSize, Alignment); 6365 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Div); 6366 const uint64_t NumElements = (Size + Div - 1) / Div; 6367 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements)); 6368 } 6369 6370 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const { 6371 if (RetTy->isVoidType()) 6372 return ABIArgInfo::getIgnore(); 6373 6374 if (getContext().getLangOpts().OpenMP && 6375 getContext().getLangOpts().OpenMPIsDevice && 6376 isUnsupportedType(getContext(), RetTy)) 6377 return coerceToIntArrayWithLimit(RetTy, getContext(), getVMContext(), 64); 6378 6379 // note: this is different from default ABI 6380 if (!RetTy->isScalarType()) 6381 return ABIArgInfo::getDirect(); 6382 6383 // Treat an enum type as its underlying type. 6384 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 6385 RetTy = EnumTy->getDecl()->getIntegerType(); 6386 6387 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 6388 : ABIArgInfo::getDirect()); 6389 } 6390 6391 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const { 6392 // Treat an enum type as its underlying type. 6393 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 6394 Ty = EnumTy->getDecl()->getIntegerType(); 6395 6396 // Return aggregates type as indirect by value 6397 if (isAggregateTypeForABI(Ty)) 6398 return getNaturalAlignIndirect(Ty, /* byval */ true); 6399 6400 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 6401 : ABIArgInfo::getDirect()); 6402 } 6403 6404 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const { 6405 if (!getCXXABI().classifyReturnType(FI)) 6406 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 6407 for (auto &I : FI.arguments()) 6408 I.info = classifyArgumentType(I.type); 6409 6410 // Always honor user-specified calling convention. 6411 if (FI.getCallingConvention() != llvm::CallingConv::C) 6412 return; 6413 6414 FI.setEffectiveCallingConvention(getRuntimeCC()); 6415 } 6416 6417 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6418 QualType Ty) const { 6419 llvm_unreachable("NVPTX does not support varargs"); 6420 } 6421 6422 void NVPTXTargetCodeGenInfo::setTargetAttributes( 6423 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 6424 if (GV->isDeclaration()) 6425 return; 6426 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 6427 if (!FD) return; 6428 6429 llvm::Function *F = cast<llvm::Function>(GV); 6430 6431 // Perform special handling in OpenCL mode 6432 if (M.getLangOpts().OpenCL) { 6433 // Use OpenCL function attributes to check for kernel functions 6434 // By default, all functions are device functions 6435 if (FD->hasAttr<OpenCLKernelAttr>()) { 6436 // OpenCL __kernel functions get kernel metadata 6437 // Create !{<func-ref>, metadata !"kernel", i32 1} node 6438 addNVVMMetadata(F, "kernel", 1); 6439 // And kernel functions are not subject to inlining 6440 F->addFnAttr(llvm::Attribute::NoInline); 6441 } 6442 } 6443 6444 // Perform special handling in CUDA mode. 6445 if (M.getLangOpts().CUDA) { 6446 // CUDA __global__ functions get a kernel metadata entry. Since 6447 // __global__ functions cannot be called from the device, we do not 6448 // need to set the noinline attribute. 6449 if (FD->hasAttr<CUDAGlobalAttr>()) { 6450 // Create !{<func-ref>, metadata !"kernel", i32 1} node 6451 addNVVMMetadata(F, "kernel", 1); 6452 } 6453 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) { 6454 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node 6455 llvm::APSInt MaxThreads(32); 6456 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext()); 6457 if (MaxThreads > 0) 6458 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue()); 6459 6460 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was 6461 // not specified in __launch_bounds__ or if the user specified a 0 value, 6462 // we don't have to add a PTX directive. 6463 if (Attr->getMinBlocks()) { 6464 llvm::APSInt MinBlocks(32); 6465 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext()); 6466 if (MinBlocks > 0) 6467 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node 6468 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue()); 6469 } 6470 } 6471 } 6472 } 6473 6474 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name, 6475 int Operand) { 6476 llvm::Module *M = F->getParent(); 6477 llvm::LLVMContext &Ctx = M->getContext(); 6478 6479 // Get "nvvm.annotations" metadata node 6480 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); 6481 6482 llvm::Metadata *MDVals[] = { 6483 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name), 6484 llvm::ConstantAsMetadata::get( 6485 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))}; 6486 // Append metadata to nvvm.annotations 6487 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 6488 } 6489 6490 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 6491 return false; 6492 } 6493 } 6494 6495 //===----------------------------------------------------------------------===// 6496 // SystemZ ABI Implementation 6497 //===----------------------------------------------------------------------===// 6498 6499 namespace { 6500 6501 class SystemZABIInfo : public SwiftABIInfo { 6502 bool HasVector; 6503 6504 public: 6505 SystemZABIInfo(CodeGenTypes &CGT, bool HV) 6506 : SwiftABIInfo(CGT), HasVector(HV) {} 6507 6508 bool isPromotableIntegerType(QualType Ty) const; 6509 bool isCompoundType(QualType Ty) const; 6510 bool isVectorArgumentType(QualType Ty) const; 6511 bool isFPArgumentType(QualType Ty) const; 6512 QualType GetSingleElementType(QualType Ty) const; 6513 6514 ABIArgInfo classifyReturnType(QualType RetTy) const; 6515 ABIArgInfo classifyArgumentType(QualType ArgTy) const; 6516 6517 void computeInfo(CGFunctionInfo &FI) const override { 6518 if (!getCXXABI().classifyReturnType(FI)) 6519 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 6520 for (auto &I : FI.arguments()) 6521 I.info = classifyArgumentType(I.type); 6522 } 6523 6524 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6525 QualType Ty) const override; 6526 6527 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars, 6528 bool asReturnValue) const override { 6529 return occupiesMoreThan(CGT, scalars, /*total*/ 4); 6530 } 6531 bool isSwiftErrorInRegister() const override { 6532 return false; 6533 } 6534 }; 6535 6536 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo { 6537 public: 6538 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector) 6539 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {} 6540 }; 6541 6542 } 6543 6544 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const { 6545 // Treat an enum type as its underlying type. 6546 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 6547 Ty = EnumTy->getDecl()->getIntegerType(); 6548 6549 // Promotable integer types are required to be promoted by the ABI. 6550 if (Ty->isPromotableIntegerType()) 6551 return true; 6552 6553 // 32-bit values must also be promoted. 6554 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 6555 switch (BT->getKind()) { 6556 case BuiltinType::Int: 6557 case BuiltinType::UInt: 6558 return true; 6559 default: 6560 return false; 6561 } 6562 return false; 6563 } 6564 6565 bool SystemZABIInfo::isCompoundType(QualType Ty) const { 6566 return (Ty->isAnyComplexType() || 6567 Ty->isVectorType() || 6568 isAggregateTypeForABI(Ty)); 6569 } 6570 6571 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const { 6572 return (HasVector && 6573 Ty->isVectorType() && 6574 getContext().getTypeSize(Ty) <= 128); 6575 } 6576 6577 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const { 6578 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) 6579 switch (BT->getKind()) { 6580 case BuiltinType::Float: 6581 case BuiltinType::Double: 6582 return true; 6583 default: 6584 return false; 6585 } 6586 6587 return false; 6588 } 6589 6590 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const { 6591 if (const RecordType *RT = Ty->getAsStructureType()) { 6592 const RecordDecl *RD = RT->getDecl(); 6593 QualType Found; 6594 6595 // If this is a C++ record, check the bases first. 6596 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 6597 for (const auto &I : CXXRD->bases()) { 6598 QualType Base = I.getType(); 6599 6600 // Empty bases don't affect things either way. 6601 if (isEmptyRecord(getContext(), Base, true)) 6602 continue; 6603 6604 if (!Found.isNull()) 6605 return Ty; 6606 Found = GetSingleElementType(Base); 6607 } 6608 6609 // Check the fields. 6610 for (const auto *FD : RD->fields()) { 6611 // For compatibility with GCC, ignore empty bitfields in C++ mode. 6612 // Unlike isSingleElementStruct(), empty structure and array fields 6613 // do count. So do anonymous bitfields that aren't zero-sized. 6614 if (getContext().getLangOpts().CPlusPlus && 6615 FD->isZeroLengthBitField(getContext())) 6616 continue; 6617 6618 // Unlike isSingleElementStruct(), arrays do not count. 6619 // Nested structures still do though. 6620 if (!Found.isNull()) 6621 return Ty; 6622 Found = GetSingleElementType(FD->getType()); 6623 } 6624 6625 // Unlike isSingleElementStruct(), trailing padding is allowed. 6626 // An 8-byte aligned struct s { float f; } is passed as a double. 6627 if (!Found.isNull()) 6628 return Found; 6629 } 6630 6631 return Ty; 6632 } 6633 6634 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6635 QualType Ty) const { 6636 // Assume that va_list type is correct; should be pointer to LLVM type: 6637 // struct { 6638 // i64 __gpr; 6639 // i64 __fpr; 6640 // i8 *__overflow_arg_area; 6641 // i8 *__reg_save_area; 6642 // }; 6643 6644 // Every non-vector argument occupies 8 bytes and is passed by preference 6645 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are 6646 // always passed on the stack. 6647 Ty = getContext().getCanonicalType(Ty); 6648 auto TyInfo = getContext().getTypeInfoInChars(Ty); 6649 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty); 6650 llvm::Type *DirectTy = ArgTy; 6651 ABIArgInfo AI = classifyArgumentType(Ty); 6652 bool IsIndirect = AI.isIndirect(); 6653 bool InFPRs = false; 6654 bool IsVector = false; 6655 CharUnits UnpaddedSize; 6656 CharUnits DirectAlign; 6657 if (IsIndirect) { 6658 DirectTy = llvm::PointerType::getUnqual(DirectTy); 6659 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8); 6660 } else { 6661 if (AI.getCoerceToType()) 6662 ArgTy = AI.getCoerceToType(); 6663 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy(); 6664 IsVector = ArgTy->isVectorTy(); 6665 UnpaddedSize = TyInfo.first; 6666 DirectAlign = TyInfo.second; 6667 } 6668 CharUnits PaddedSize = CharUnits::fromQuantity(8); 6669 if (IsVector && UnpaddedSize > PaddedSize) 6670 PaddedSize = CharUnits::fromQuantity(16); 6671 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size."); 6672 6673 CharUnits Padding = (PaddedSize - UnpaddedSize); 6674 6675 llvm::Type *IndexTy = CGF.Int64Ty; 6676 llvm::Value *PaddedSizeV = 6677 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity()); 6678 6679 if (IsVector) { 6680 // Work out the address of a vector argument on the stack. 6681 // Vector arguments are always passed in the high bits of a 6682 // single (8 byte) or double (16 byte) stack slot. 6683 Address OverflowArgAreaPtr = 6684 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 6685 Address OverflowArgArea = 6686 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 6687 TyInfo.second); 6688 Address MemAddr = 6689 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr"); 6690 6691 // Update overflow_arg_area_ptr pointer 6692 llvm::Value *NewOverflowArgArea = 6693 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV, 6694 "overflow_arg_area"); 6695 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 6696 6697 return MemAddr; 6698 } 6699 6700 assert(PaddedSize.getQuantity() == 8); 6701 6702 unsigned MaxRegs, RegCountField, RegSaveIndex; 6703 CharUnits RegPadding; 6704 if (InFPRs) { 6705 MaxRegs = 4; // Maximum of 4 FPR arguments 6706 RegCountField = 1; // __fpr 6707 RegSaveIndex = 16; // save offset for f0 6708 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR 6709 } else { 6710 MaxRegs = 5; // Maximum of 5 GPR arguments 6711 RegCountField = 0; // __gpr 6712 RegSaveIndex = 2; // save offset for r2 6713 RegPadding = Padding; // values are passed in the low bits of a GPR 6714 } 6715 6716 Address RegCountPtr = 6717 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr"); 6718 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count"); 6719 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs); 6720 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV, 6721 "fits_in_regs"); 6722 6723 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg"); 6724 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem"); 6725 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end"); 6726 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock); 6727 6728 // Emit code to load the value if it was passed in registers. 6729 CGF.EmitBlock(InRegBlock); 6730 6731 // Work out the address of an argument register. 6732 llvm::Value *ScaledRegCount = 6733 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count"); 6734 llvm::Value *RegBase = 6735 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity() 6736 + RegPadding.getQuantity()); 6737 llvm::Value *RegOffset = 6738 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset"); 6739 Address RegSaveAreaPtr = 6740 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr"); 6741 llvm::Value *RegSaveArea = 6742 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area"); 6743 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset, 6744 "raw_reg_addr"), 6745 PaddedSize); 6746 Address RegAddr = 6747 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr"); 6748 6749 // Update the register count 6750 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1); 6751 llvm::Value *NewRegCount = 6752 CGF.Builder.CreateAdd(RegCount, One, "reg_count"); 6753 CGF.Builder.CreateStore(NewRegCount, RegCountPtr); 6754 CGF.EmitBranch(ContBlock); 6755 6756 // Emit code to load the value if it was passed in memory. 6757 CGF.EmitBlock(InMemBlock); 6758 6759 // Work out the address of a stack argument. 6760 Address OverflowArgAreaPtr = 6761 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr"); 6762 Address OverflowArgArea = 6763 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"), 6764 PaddedSize); 6765 Address RawMemAddr = 6766 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr"); 6767 Address MemAddr = 6768 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr"); 6769 6770 // Update overflow_arg_area_ptr pointer 6771 llvm::Value *NewOverflowArgArea = 6772 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV, 6773 "overflow_arg_area"); 6774 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr); 6775 CGF.EmitBranch(ContBlock); 6776 6777 // Return the appropriate result. 6778 CGF.EmitBlock(ContBlock); 6779 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, 6780 MemAddr, InMemBlock, "va_arg.addr"); 6781 6782 if (IsIndirect) 6783 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"), 6784 TyInfo.second); 6785 6786 return ResAddr; 6787 } 6788 6789 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const { 6790 if (RetTy->isVoidType()) 6791 return ABIArgInfo::getIgnore(); 6792 if (isVectorArgumentType(RetTy)) 6793 return ABIArgInfo::getDirect(); 6794 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64) 6795 return getNaturalAlignIndirect(RetTy); 6796 return (isPromotableIntegerType(RetTy) ? ABIArgInfo::getExtend(RetTy) 6797 : ABIArgInfo::getDirect()); 6798 } 6799 6800 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const { 6801 // Handle the generic C++ ABI. 6802 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 6803 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 6804 6805 // Integers and enums are extended to full register width. 6806 if (isPromotableIntegerType(Ty)) 6807 return ABIArgInfo::getExtend(Ty); 6808 6809 // Handle vector types and vector-like structure types. Note that 6810 // as opposed to float-like structure types, we do not allow any 6811 // padding for vector-like structures, so verify the sizes match. 6812 uint64_t Size = getContext().getTypeSize(Ty); 6813 QualType SingleElementTy = GetSingleElementType(Ty); 6814 if (isVectorArgumentType(SingleElementTy) && 6815 getContext().getTypeSize(SingleElementTy) == Size) 6816 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy)); 6817 6818 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly. 6819 if (Size != 8 && Size != 16 && Size != 32 && Size != 64) 6820 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 6821 6822 // Handle small structures. 6823 if (const RecordType *RT = Ty->getAs<RecordType>()) { 6824 // Structures with flexible arrays have variable length, so really 6825 // fail the size test above. 6826 const RecordDecl *RD = RT->getDecl(); 6827 if (RD->hasFlexibleArrayMember()) 6828 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 6829 6830 // The structure is passed as an unextended integer, a float, or a double. 6831 llvm::Type *PassTy; 6832 if (isFPArgumentType(SingleElementTy)) { 6833 assert(Size == 32 || Size == 64); 6834 if (Size == 32) 6835 PassTy = llvm::Type::getFloatTy(getVMContext()); 6836 else 6837 PassTy = llvm::Type::getDoubleTy(getVMContext()); 6838 } else 6839 PassTy = llvm::IntegerType::get(getVMContext(), Size); 6840 return ABIArgInfo::getDirect(PassTy); 6841 } 6842 6843 // Non-structure compounds are passed indirectly. 6844 if (isCompoundType(Ty)) 6845 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 6846 6847 return ABIArgInfo::getDirect(nullptr); 6848 } 6849 6850 //===----------------------------------------------------------------------===// 6851 // MSP430 ABI Implementation 6852 //===----------------------------------------------------------------------===// 6853 6854 namespace { 6855 6856 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo { 6857 public: 6858 MSP430TargetCodeGenInfo(CodeGenTypes &CGT) 6859 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 6860 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6861 CodeGen::CodeGenModule &M) const override; 6862 }; 6863 6864 } 6865 6866 void MSP430TargetCodeGenInfo::setTargetAttributes( 6867 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 6868 if (GV->isDeclaration()) 6869 return; 6870 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 6871 const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>(); 6872 if (!InterruptAttr) 6873 return; 6874 6875 // Handle 'interrupt' attribute: 6876 llvm::Function *F = cast<llvm::Function>(GV); 6877 6878 // Step 1: Set ISR calling convention. 6879 F->setCallingConv(llvm::CallingConv::MSP430_INTR); 6880 6881 // Step 2: Add attributes goodness. 6882 F->addFnAttr(llvm::Attribute::NoInline); 6883 F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber())); 6884 } 6885 } 6886 6887 //===----------------------------------------------------------------------===// 6888 // MIPS ABI Implementation. This works for both little-endian and 6889 // big-endian variants. 6890 //===----------------------------------------------------------------------===// 6891 6892 namespace { 6893 class MipsABIInfo : public ABIInfo { 6894 bool IsO32; 6895 unsigned MinABIStackAlignInBytes, StackAlignInBytes; 6896 void CoerceToIntArgs(uint64_t TySize, 6897 SmallVectorImpl<llvm::Type *> &ArgList) const; 6898 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const; 6899 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const; 6900 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const; 6901 public: 6902 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) : 6903 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8), 6904 StackAlignInBytes(IsO32 ? 8 : 16) {} 6905 6906 ABIArgInfo classifyReturnType(QualType RetTy) const; 6907 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const; 6908 void computeInfo(CGFunctionInfo &FI) const override; 6909 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 6910 QualType Ty) const override; 6911 ABIArgInfo extendType(QualType Ty) const; 6912 }; 6913 6914 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo { 6915 unsigned SizeOfUnwindException; 6916 public: 6917 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32) 6918 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)), 6919 SizeOfUnwindException(IsO32 ? 24 : 32) {} 6920 6921 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override { 6922 return 29; 6923 } 6924 6925 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 6926 CodeGen::CodeGenModule &CGM) const override { 6927 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 6928 if (!FD) return; 6929 llvm::Function *Fn = cast<llvm::Function>(GV); 6930 6931 if (FD->hasAttr<MipsLongCallAttr>()) 6932 Fn->addFnAttr("long-call"); 6933 else if (FD->hasAttr<MipsShortCallAttr>()) 6934 Fn->addFnAttr("short-call"); 6935 6936 // Other attributes do not have a meaning for declarations. 6937 if (GV->isDeclaration()) 6938 return; 6939 6940 if (FD->hasAttr<Mips16Attr>()) { 6941 Fn->addFnAttr("mips16"); 6942 } 6943 else if (FD->hasAttr<NoMips16Attr>()) { 6944 Fn->addFnAttr("nomips16"); 6945 } 6946 6947 if (FD->hasAttr<MicroMipsAttr>()) 6948 Fn->addFnAttr("micromips"); 6949 else if (FD->hasAttr<NoMicroMipsAttr>()) 6950 Fn->addFnAttr("nomicromips"); 6951 6952 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>(); 6953 if (!Attr) 6954 return; 6955 6956 const char *Kind; 6957 switch (Attr->getInterrupt()) { 6958 case MipsInterruptAttr::eic: Kind = "eic"; break; 6959 case MipsInterruptAttr::sw0: Kind = "sw0"; break; 6960 case MipsInterruptAttr::sw1: Kind = "sw1"; break; 6961 case MipsInterruptAttr::hw0: Kind = "hw0"; break; 6962 case MipsInterruptAttr::hw1: Kind = "hw1"; break; 6963 case MipsInterruptAttr::hw2: Kind = "hw2"; break; 6964 case MipsInterruptAttr::hw3: Kind = "hw3"; break; 6965 case MipsInterruptAttr::hw4: Kind = "hw4"; break; 6966 case MipsInterruptAttr::hw5: Kind = "hw5"; break; 6967 } 6968 6969 Fn->addFnAttr("interrupt", Kind); 6970 6971 } 6972 6973 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 6974 llvm::Value *Address) const override; 6975 6976 unsigned getSizeOfUnwindException() const override { 6977 return SizeOfUnwindException; 6978 } 6979 }; 6980 } 6981 6982 void MipsABIInfo::CoerceToIntArgs( 6983 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const { 6984 llvm::IntegerType *IntTy = 6985 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8); 6986 6987 // Add (TySize / MinABIStackAlignInBytes) args of IntTy. 6988 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N) 6989 ArgList.push_back(IntTy); 6990 6991 // If necessary, add one more integer type to ArgList. 6992 unsigned R = TySize % (MinABIStackAlignInBytes * 8); 6993 6994 if (R) 6995 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R)); 6996 } 6997 6998 // In N32/64, an aligned double precision floating point field is passed in 6999 // a register. 7000 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const { 7001 SmallVector<llvm::Type*, 8> ArgList, IntArgList; 7002 7003 if (IsO32) { 7004 CoerceToIntArgs(TySize, ArgList); 7005 return llvm::StructType::get(getVMContext(), ArgList); 7006 } 7007 7008 if (Ty->isComplexType()) 7009 return CGT.ConvertType(Ty); 7010 7011 const RecordType *RT = Ty->getAs<RecordType>(); 7012 7013 // Unions/vectors are passed in integer registers. 7014 if (!RT || !RT->isStructureOrClassType()) { 7015 CoerceToIntArgs(TySize, ArgList); 7016 return llvm::StructType::get(getVMContext(), ArgList); 7017 } 7018 7019 const RecordDecl *RD = RT->getDecl(); 7020 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7021 assert(!(TySize % 8) && "Size of structure must be multiple of 8."); 7022 7023 uint64_t LastOffset = 0; 7024 unsigned idx = 0; 7025 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64); 7026 7027 // Iterate over fields in the struct/class and check if there are any aligned 7028 // double fields. 7029 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end(); 7030 i != e; ++i, ++idx) { 7031 const QualType Ty = i->getType(); 7032 const BuiltinType *BT = Ty->getAs<BuiltinType>(); 7033 7034 if (!BT || BT->getKind() != BuiltinType::Double) 7035 continue; 7036 7037 uint64_t Offset = Layout.getFieldOffset(idx); 7038 if (Offset % 64) // Ignore doubles that are not aligned. 7039 continue; 7040 7041 // Add ((Offset - LastOffset) / 64) args of type i64. 7042 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j) 7043 ArgList.push_back(I64); 7044 7045 // Add double type. 7046 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext())); 7047 LastOffset = Offset + 64; 7048 } 7049 7050 CoerceToIntArgs(TySize - LastOffset, IntArgList); 7051 ArgList.append(IntArgList.begin(), IntArgList.end()); 7052 7053 return llvm::StructType::get(getVMContext(), ArgList); 7054 } 7055 7056 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset, 7057 uint64_t Offset) const { 7058 if (OrigOffset + MinABIStackAlignInBytes > Offset) 7059 return nullptr; 7060 7061 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8); 7062 } 7063 7064 ABIArgInfo 7065 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const { 7066 Ty = useFirstFieldIfTransparentUnion(Ty); 7067 7068 uint64_t OrigOffset = Offset; 7069 uint64_t TySize = getContext().getTypeSize(Ty); 7070 uint64_t Align = getContext().getTypeAlign(Ty) / 8; 7071 7072 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes), 7073 (uint64_t)StackAlignInBytes); 7074 unsigned CurrOffset = llvm::alignTo(Offset, Align); 7075 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8; 7076 7077 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) { 7078 // Ignore empty aggregates. 7079 if (TySize == 0) 7080 return ABIArgInfo::getIgnore(); 7081 7082 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 7083 Offset = OrigOffset + MinABIStackAlignInBytes; 7084 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7085 } 7086 7087 // If we have reached here, aggregates are passed directly by coercing to 7088 // another structure type. Padding is inserted if the offset of the 7089 // aggregate is unaligned. 7090 ABIArgInfo ArgInfo = 7091 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0, 7092 getPaddingType(OrigOffset, CurrOffset)); 7093 ArgInfo.setInReg(true); 7094 return ArgInfo; 7095 } 7096 7097 // Treat an enum type as its underlying type. 7098 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7099 Ty = EnumTy->getDecl()->getIntegerType(); 7100 7101 // All integral types are promoted to the GPR width. 7102 if (Ty->isIntegralOrEnumerationType()) 7103 return extendType(Ty); 7104 7105 return ABIArgInfo::getDirect( 7106 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset)); 7107 } 7108 7109 llvm::Type* 7110 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const { 7111 const RecordType *RT = RetTy->getAs<RecordType>(); 7112 SmallVector<llvm::Type*, 8> RTList; 7113 7114 if (RT && RT->isStructureOrClassType()) { 7115 const RecordDecl *RD = RT->getDecl(); 7116 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 7117 unsigned FieldCnt = Layout.getFieldCount(); 7118 7119 // N32/64 returns struct/classes in floating point registers if the 7120 // following conditions are met: 7121 // 1. The size of the struct/class is no larger than 128-bit. 7122 // 2. The struct/class has one or two fields all of which are floating 7123 // point types. 7124 // 3. The offset of the first field is zero (this follows what gcc does). 7125 // 7126 // Any other composite results are returned in integer registers. 7127 // 7128 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) { 7129 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end(); 7130 for (; b != e; ++b) { 7131 const BuiltinType *BT = b->getType()->getAs<BuiltinType>(); 7132 7133 if (!BT || !BT->isFloatingPoint()) 7134 break; 7135 7136 RTList.push_back(CGT.ConvertType(b->getType())); 7137 } 7138 7139 if (b == e) 7140 return llvm::StructType::get(getVMContext(), RTList, 7141 RD->hasAttr<PackedAttr>()); 7142 7143 RTList.clear(); 7144 } 7145 } 7146 7147 CoerceToIntArgs(Size, RTList); 7148 return llvm::StructType::get(getVMContext(), RTList); 7149 } 7150 7151 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const { 7152 uint64_t Size = getContext().getTypeSize(RetTy); 7153 7154 if (RetTy->isVoidType()) 7155 return ABIArgInfo::getIgnore(); 7156 7157 // O32 doesn't treat zero-sized structs differently from other structs. 7158 // However, N32/N64 ignores zero sized return values. 7159 if (!IsO32 && Size == 0) 7160 return ABIArgInfo::getIgnore(); 7161 7162 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) { 7163 if (Size <= 128) { 7164 if (RetTy->isAnyComplexType()) 7165 return ABIArgInfo::getDirect(); 7166 7167 // O32 returns integer vectors in registers and N32/N64 returns all small 7168 // aggregates in registers. 7169 if (!IsO32 || 7170 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) { 7171 ABIArgInfo ArgInfo = 7172 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size)); 7173 ArgInfo.setInReg(true); 7174 return ArgInfo; 7175 } 7176 } 7177 7178 return getNaturalAlignIndirect(RetTy); 7179 } 7180 7181 // Treat an enum type as its underlying type. 7182 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7183 RetTy = EnumTy->getDecl()->getIntegerType(); 7184 7185 if (RetTy->isPromotableIntegerType()) 7186 return ABIArgInfo::getExtend(RetTy); 7187 7188 if ((RetTy->isUnsignedIntegerOrEnumerationType() || 7189 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32) 7190 return ABIArgInfo::getSignExtend(RetTy); 7191 7192 return ABIArgInfo::getDirect(); 7193 } 7194 7195 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const { 7196 ABIArgInfo &RetInfo = FI.getReturnInfo(); 7197 if (!getCXXABI().classifyReturnType(FI)) 7198 RetInfo = classifyReturnType(FI.getReturnType()); 7199 7200 // Check if a pointer to an aggregate is passed as a hidden argument. 7201 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0; 7202 7203 for (auto &I : FI.arguments()) 7204 I.info = classifyArgumentType(I.type, Offset); 7205 } 7206 7207 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7208 QualType OrigTy) const { 7209 QualType Ty = OrigTy; 7210 7211 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64. 7212 // Pointers are also promoted in the same way but this only matters for N32. 7213 unsigned SlotSizeInBits = IsO32 ? 32 : 64; 7214 unsigned PtrWidth = getTarget().getPointerWidth(0); 7215 bool DidPromote = false; 7216 if ((Ty->isIntegerType() && 7217 getContext().getIntWidth(Ty) < SlotSizeInBits) || 7218 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) { 7219 DidPromote = true; 7220 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits, 7221 Ty->isSignedIntegerType()); 7222 } 7223 7224 auto TyInfo = getContext().getTypeInfoInChars(Ty); 7225 7226 // The alignment of things in the argument area is never larger than 7227 // StackAlignInBytes. 7228 TyInfo.second = 7229 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes)); 7230 7231 // MinABIStackAlignInBytes is the size of argument slots on the stack. 7232 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes); 7233 7234 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 7235 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true); 7236 7237 7238 // If there was a promotion, "unpromote" into a temporary. 7239 // TODO: can we just use a pointer into a subset of the original slot? 7240 if (DidPromote) { 7241 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp"); 7242 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr); 7243 7244 // Truncate down to the right width. 7245 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType() 7246 : CGF.IntPtrTy); 7247 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy); 7248 if (OrigTy->isPointerType()) 7249 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType()); 7250 7251 CGF.Builder.CreateStore(V, Temp); 7252 Addr = Temp; 7253 } 7254 7255 return Addr; 7256 } 7257 7258 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const { 7259 int TySize = getContext().getTypeSize(Ty); 7260 7261 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended. 7262 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 7263 return ABIArgInfo::getSignExtend(Ty); 7264 7265 return ABIArgInfo::getExtend(Ty); 7266 } 7267 7268 bool 7269 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 7270 llvm::Value *Address) const { 7271 // This information comes from gcc's implementation, which seems to 7272 // as canonical as it gets. 7273 7274 // Everything on MIPS is 4 bytes. Double-precision FP registers 7275 // are aliased to pairs of single-precision FP registers. 7276 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4); 7277 7278 // 0-31 are the general purpose registers, $0 - $31. 7279 // 32-63 are the floating-point registers, $f0 - $f31. 7280 // 64 and 65 are the multiply/divide registers, $hi and $lo. 7281 // 66 is the (notional, I think) register for signal-handler return. 7282 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65); 7283 7284 // 67-74 are the floating-point status registers, $fcc0 - $fcc7. 7285 // They are one bit wide and ignored here. 7286 7287 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31. 7288 // (coprocessor 1 is the FP unit) 7289 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31. 7290 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31. 7291 // 176-181 are the DSP accumulator registers. 7292 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181); 7293 return false; 7294 } 7295 7296 //===----------------------------------------------------------------------===// 7297 // AVR ABI Implementation. 7298 //===----------------------------------------------------------------------===// 7299 7300 namespace { 7301 class AVRTargetCodeGenInfo : public TargetCodeGenInfo { 7302 public: 7303 AVRTargetCodeGenInfo(CodeGenTypes &CGT) 7304 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { } 7305 7306 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7307 CodeGen::CodeGenModule &CGM) const override { 7308 if (GV->isDeclaration()) 7309 return; 7310 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 7311 if (!FD) return; 7312 auto *Fn = cast<llvm::Function>(GV); 7313 7314 if (FD->getAttr<AVRInterruptAttr>()) 7315 Fn->addFnAttr("interrupt"); 7316 7317 if (FD->getAttr<AVRSignalAttr>()) 7318 Fn->addFnAttr("signal"); 7319 } 7320 }; 7321 } 7322 7323 //===----------------------------------------------------------------------===// 7324 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults. 7325 // Currently subclassed only to implement custom OpenCL C function attribute 7326 // handling. 7327 //===----------------------------------------------------------------------===// 7328 7329 namespace { 7330 7331 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo { 7332 public: 7333 TCETargetCodeGenInfo(CodeGenTypes &CGT) 7334 : DefaultTargetCodeGenInfo(CGT) {} 7335 7336 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7337 CodeGen::CodeGenModule &M) const override; 7338 }; 7339 7340 void TCETargetCodeGenInfo::setTargetAttributes( 7341 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7342 if (GV->isDeclaration()) 7343 return; 7344 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7345 if (!FD) return; 7346 7347 llvm::Function *F = cast<llvm::Function>(GV); 7348 7349 if (M.getLangOpts().OpenCL) { 7350 if (FD->hasAttr<OpenCLKernelAttr>()) { 7351 // OpenCL C Kernel functions are not subject to inlining 7352 F->addFnAttr(llvm::Attribute::NoInline); 7353 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>(); 7354 if (Attr) { 7355 // Convert the reqd_work_group_size() attributes to metadata. 7356 llvm::LLVMContext &Context = F->getContext(); 7357 llvm::NamedMDNode *OpenCLMetadata = 7358 M.getModule().getOrInsertNamedMetadata( 7359 "opencl.kernel_wg_size_info"); 7360 7361 SmallVector<llvm::Metadata *, 5> Operands; 7362 Operands.push_back(llvm::ConstantAsMetadata::get(F)); 7363 7364 Operands.push_back( 7365 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 7366 M.Int32Ty, llvm::APInt(32, Attr->getXDim())))); 7367 Operands.push_back( 7368 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 7369 M.Int32Ty, llvm::APInt(32, Attr->getYDim())))); 7370 Operands.push_back( 7371 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue( 7372 M.Int32Ty, llvm::APInt(32, Attr->getZDim())))); 7373 7374 // Add a boolean constant operand for "required" (true) or "hint" 7375 // (false) for implementing the work_group_size_hint attr later. 7376 // Currently always true as the hint is not yet implemented. 7377 Operands.push_back( 7378 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context))); 7379 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands)); 7380 } 7381 } 7382 } 7383 } 7384 7385 } 7386 7387 //===----------------------------------------------------------------------===// 7388 // Hexagon ABI Implementation 7389 //===----------------------------------------------------------------------===// 7390 7391 namespace { 7392 7393 class HexagonABIInfo : public ABIInfo { 7394 7395 7396 public: 7397 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 7398 7399 private: 7400 7401 ABIArgInfo classifyReturnType(QualType RetTy) const; 7402 ABIArgInfo classifyArgumentType(QualType RetTy) const; 7403 7404 void computeInfo(CGFunctionInfo &FI) const override; 7405 7406 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7407 QualType Ty) const override; 7408 }; 7409 7410 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo { 7411 public: 7412 HexagonTargetCodeGenInfo(CodeGenTypes &CGT) 7413 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {} 7414 7415 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 7416 return 29; 7417 } 7418 }; 7419 7420 } 7421 7422 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const { 7423 if (!getCXXABI().classifyReturnType(FI)) 7424 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7425 for (auto &I : FI.arguments()) 7426 I.info = classifyArgumentType(I.type); 7427 } 7428 7429 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const { 7430 if (!isAggregateTypeForABI(Ty)) { 7431 // Treat an enum type as its underlying type. 7432 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 7433 Ty = EnumTy->getDecl()->getIntegerType(); 7434 7435 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty) 7436 : ABIArgInfo::getDirect()); 7437 } 7438 7439 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 7440 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7441 7442 // Ignore empty records. 7443 if (isEmptyRecord(getContext(), Ty, true)) 7444 return ABIArgInfo::getIgnore(); 7445 7446 uint64_t Size = getContext().getTypeSize(Ty); 7447 if (Size > 64) 7448 return getNaturalAlignIndirect(Ty, /*ByVal=*/true); 7449 // Pass in the smallest viable integer type. 7450 else if (Size > 32) 7451 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext())); 7452 else if (Size > 16) 7453 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 7454 else if (Size > 8) 7455 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 7456 else 7457 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 7458 } 7459 7460 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const { 7461 if (RetTy->isVoidType()) 7462 return ABIArgInfo::getIgnore(); 7463 7464 // Large vector types should be returned via memory. 7465 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64) 7466 return getNaturalAlignIndirect(RetTy); 7467 7468 if (!isAggregateTypeForABI(RetTy)) { 7469 // Treat an enum type as its underlying type. 7470 if (const EnumType *EnumTy = RetTy->getAs<EnumType>()) 7471 RetTy = EnumTy->getDecl()->getIntegerType(); 7472 7473 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy) 7474 : ABIArgInfo::getDirect()); 7475 } 7476 7477 if (isEmptyRecord(getContext(), RetTy, true)) 7478 return ABIArgInfo::getIgnore(); 7479 7480 // Aggregates <= 8 bytes are returned in r0; other aggregates 7481 // are returned indirectly. 7482 uint64_t Size = getContext().getTypeSize(RetTy); 7483 if (Size <= 64) { 7484 // Return in the smallest viable integer type. 7485 if (Size <= 8) 7486 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext())); 7487 if (Size <= 16) 7488 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 7489 if (Size <= 32) 7490 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 7491 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext())); 7492 } 7493 7494 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true); 7495 } 7496 7497 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 7498 QualType Ty) const { 7499 // FIXME: Someone needs to audit that this handle alignment correctly. 7500 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 7501 getContext().getTypeInfoInChars(Ty), 7502 CharUnits::fromQuantity(4), 7503 /*AllowHigherAlign*/ true); 7504 } 7505 7506 //===----------------------------------------------------------------------===// 7507 // Lanai ABI Implementation 7508 //===----------------------------------------------------------------------===// 7509 7510 namespace { 7511 class LanaiABIInfo : public DefaultABIInfo { 7512 public: 7513 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 7514 7515 bool shouldUseInReg(QualType Ty, CCState &State) const; 7516 7517 void computeInfo(CGFunctionInfo &FI) const override { 7518 CCState State(FI.getCallingConvention()); 7519 // Lanai uses 4 registers to pass arguments unless the function has the 7520 // regparm attribute set. 7521 if (FI.getHasRegParm()) { 7522 State.FreeRegs = FI.getRegParm(); 7523 } else { 7524 State.FreeRegs = 4; 7525 } 7526 7527 if (!getCXXABI().classifyReturnType(FI)) 7528 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7529 for (auto &I : FI.arguments()) 7530 I.info = classifyArgumentType(I.type, State); 7531 } 7532 7533 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const; 7534 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const; 7535 }; 7536 } // end anonymous namespace 7537 7538 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const { 7539 unsigned Size = getContext().getTypeSize(Ty); 7540 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U; 7541 7542 if (SizeInRegs == 0) 7543 return false; 7544 7545 if (SizeInRegs > State.FreeRegs) { 7546 State.FreeRegs = 0; 7547 return false; 7548 } 7549 7550 State.FreeRegs -= SizeInRegs; 7551 7552 return true; 7553 } 7554 7555 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal, 7556 CCState &State) const { 7557 if (!ByVal) { 7558 if (State.FreeRegs) { 7559 --State.FreeRegs; // Non-byval indirects just use one pointer. 7560 return getNaturalAlignIndirectInReg(Ty); 7561 } 7562 return getNaturalAlignIndirect(Ty, false); 7563 } 7564 7565 // Compute the byval alignment. 7566 const unsigned MinABIStackAlignInBytes = 4; 7567 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 7568 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 7569 /*Realign=*/TypeAlign > 7570 MinABIStackAlignInBytes); 7571 } 7572 7573 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty, 7574 CCState &State) const { 7575 // Check with the C++ ABI first. 7576 const RecordType *RT = Ty->getAs<RecordType>(); 7577 if (RT) { 7578 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 7579 if (RAA == CGCXXABI::RAA_Indirect) { 7580 return getIndirectResult(Ty, /*ByVal=*/false, State); 7581 } else if (RAA == CGCXXABI::RAA_DirectInMemory) { 7582 return getNaturalAlignIndirect(Ty, /*ByRef=*/true); 7583 } 7584 } 7585 7586 if (isAggregateTypeForABI(Ty)) { 7587 // Structures with flexible arrays are always indirect. 7588 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 7589 return getIndirectResult(Ty, /*ByVal=*/true, State); 7590 7591 // Ignore empty structs/unions. 7592 if (isEmptyRecord(getContext(), Ty, true)) 7593 return ABIArgInfo::getIgnore(); 7594 7595 llvm::LLVMContext &LLVMContext = getVMContext(); 7596 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32; 7597 if (SizeInRegs <= State.FreeRegs) { 7598 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 7599 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 7600 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 7601 State.FreeRegs -= SizeInRegs; 7602 return ABIArgInfo::getDirectInReg(Result); 7603 } else { 7604 State.FreeRegs = 0; 7605 } 7606 return getIndirectResult(Ty, true, State); 7607 } 7608 7609 // Treat an enum type as its underlying type. 7610 if (const auto *EnumTy = Ty->getAs<EnumType>()) 7611 Ty = EnumTy->getDecl()->getIntegerType(); 7612 7613 bool InReg = shouldUseInReg(Ty, State); 7614 if (Ty->isPromotableIntegerType()) { 7615 if (InReg) 7616 return ABIArgInfo::getDirectInReg(); 7617 return ABIArgInfo::getExtend(Ty); 7618 } 7619 if (InReg) 7620 return ABIArgInfo::getDirectInReg(); 7621 return ABIArgInfo::getDirect(); 7622 } 7623 7624 namespace { 7625 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo { 7626 public: 7627 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 7628 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {} 7629 }; 7630 } 7631 7632 //===----------------------------------------------------------------------===// 7633 // AMDGPU ABI Implementation 7634 //===----------------------------------------------------------------------===// 7635 7636 namespace { 7637 7638 class AMDGPUABIInfo final : public DefaultABIInfo { 7639 private: 7640 static const unsigned MaxNumRegsForArgsRet = 16; 7641 7642 unsigned numRegsForType(QualType Ty) const; 7643 7644 bool isHomogeneousAggregateBaseType(QualType Ty) const override; 7645 bool isHomogeneousAggregateSmallEnough(const Type *Base, 7646 uint64_t Members) const override; 7647 7648 public: 7649 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) : 7650 DefaultABIInfo(CGT) {} 7651 7652 ABIArgInfo classifyReturnType(QualType RetTy) const; 7653 ABIArgInfo classifyKernelArgumentType(QualType Ty) const; 7654 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const; 7655 7656 void computeInfo(CGFunctionInfo &FI) const override; 7657 }; 7658 7659 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const { 7660 return true; 7661 } 7662 7663 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough( 7664 const Type *Base, uint64_t Members) const { 7665 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32; 7666 7667 // Homogeneous Aggregates may occupy at most 16 registers. 7668 return Members * NumRegs <= MaxNumRegsForArgsRet; 7669 } 7670 7671 /// Estimate number of registers the type will use when passed in registers. 7672 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const { 7673 unsigned NumRegs = 0; 7674 7675 if (const VectorType *VT = Ty->getAs<VectorType>()) { 7676 // Compute from the number of elements. The reported size is based on the 7677 // in-memory size, which includes the padding 4th element for 3-vectors. 7678 QualType EltTy = VT->getElementType(); 7679 unsigned EltSize = getContext().getTypeSize(EltTy); 7680 7681 // 16-bit element vectors should be passed as packed. 7682 if (EltSize == 16) 7683 return (VT->getNumElements() + 1) / 2; 7684 7685 unsigned EltNumRegs = (EltSize + 31) / 32; 7686 return EltNumRegs * VT->getNumElements(); 7687 } 7688 7689 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7690 const RecordDecl *RD = RT->getDecl(); 7691 assert(!RD->hasFlexibleArrayMember()); 7692 7693 for (const FieldDecl *Field : RD->fields()) { 7694 QualType FieldTy = Field->getType(); 7695 NumRegs += numRegsForType(FieldTy); 7696 } 7697 7698 return NumRegs; 7699 } 7700 7701 return (getContext().getTypeSize(Ty) + 31) / 32; 7702 } 7703 7704 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const { 7705 llvm::CallingConv::ID CC = FI.getCallingConvention(); 7706 7707 if (!getCXXABI().classifyReturnType(FI)) 7708 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 7709 7710 unsigned NumRegsLeft = MaxNumRegsForArgsRet; 7711 for (auto &Arg : FI.arguments()) { 7712 if (CC == llvm::CallingConv::AMDGPU_KERNEL) { 7713 Arg.info = classifyKernelArgumentType(Arg.type); 7714 } else { 7715 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft); 7716 } 7717 } 7718 } 7719 7720 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const { 7721 if (isAggregateTypeForABI(RetTy)) { 7722 // Records with non-trivial destructors/copy-constructors should not be 7723 // returned by value. 7724 if (!getRecordArgABI(RetTy, getCXXABI())) { 7725 // Ignore empty structs/unions. 7726 if (isEmptyRecord(getContext(), RetTy, true)) 7727 return ABIArgInfo::getIgnore(); 7728 7729 // Lower single-element structs to just return a regular value. 7730 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext())) 7731 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 7732 7733 if (const RecordType *RT = RetTy->getAs<RecordType>()) { 7734 const RecordDecl *RD = RT->getDecl(); 7735 if (RD->hasFlexibleArrayMember()) 7736 return DefaultABIInfo::classifyReturnType(RetTy); 7737 } 7738 7739 // Pack aggregates <= 4 bytes into single VGPR or pair. 7740 uint64_t Size = getContext().getTypeSize(RetTy); 7741 if (Size <= 16) 7742 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 7743 7744 if (Size <= 32) 7745 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 7746 7747 if (Size <= 64) { 7748 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 7749 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 7750 } 7751 7752 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet) 7753 return ABIArgInfo::getDirect(); 7754 } 7755 } 7756 7757 // Otherwise just do the default thing. 7758 return DefaultABIInfo::classifyReturnType(RetTy); 7759 } 7760 7761 /// For kernels all parameters are really passed in a special buffer. It doesn't 7762 /// make sense to pass anything byval, so everything must be direct. 7763 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const { 7764 Ty = useFirstFieldIfTransparentUnion(Ty); 7765 7766 // TODO: Can we omit empty structs? 7767 7768 // Coerce single element structs to its element. 7769 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 7770 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 7771 7772 // If we set CanBeFlattened to true, CodeGen will expand the struct to its 7773 // individual elements, which confuses the Clover OpenCL backend; therefore we 7774 // have to set it to false here. Other args of getDirect() are just defaults. 7775 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false); 7776 } 7777 7778 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty, 7779 unsigned &NumRegsLeft) const { 7780 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow"); 7781 7782 Ty = useFirstFieldIfTransparentUnion(Ty); 7783 7784 if (isAggregateTypeForABI(Ty)) { 7785 // Records with non-trivial destructors/copy-constructors should not be 7786 // passed by value. 7787 if (auto RAA = getRecordArgABI(Ty, getCXXABI())) 7788 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 7789 7790 // Ignore empty structs/unions. 7791 if (isEmptyRecord(getContext(), Ty, true)) 7792 return ABIArgInfo::getIgnore(); 7793 7794 // Lower single-element structs to just pass a regular value. TODO: We 7795 // could do reasonable-size multiple-element structs too, using getExpand(), 7796 // though watch out for things like bitfields. 7797 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext())) 7798 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0))); 7799 7800 if (const RecordType *RT = Ty->getAs<RecordType>()) { 7801 const RecordDecl *RD = RT->getDecl(); 7802 if (RD->hasFlexibleArrayMember()) 7803 return DefaultABIInfo::classifyArgumentType(Ty); 7804 } 7805 7806 // Pack aggregates <= 8 bytes into single VGPR or pair. 7807 uint64_t Size = getContext().getTypeSize(Ty); 7808 if (Size <= 64) { 7809 unsigned NumRegs = (Size + 31) / 32; 7810 NumRegsLeft -= std::min(NumRegsLeft, NumRegs); 7811 7812 if (Size <= 16) 7813 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext())); 7814 7815 if (Size <= 32) 7816 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext())); 7817 7818 // XXX: Should this be i64 instead, and should the limit increase? 7819 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext()); 7820 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2)); 7821 } 7822 7823 if (NumRegsLeft > 0) { 7824 unsigned NumRegs = numRegsForType(Ty); 7825 if (NumRegsLeft >= NumRegs) { 7826 NumRegsLeft -= NumRegs; 7827 return ABIArgInfo::getDirect(); 7828 } 7829 } 7830 } 7831 7832 // Otherwise just do the default thing. 7833 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty); 7834 if (!ArgInfo.isIndirect()) { 7835 unsigned NumRegs = numRegsForType(Ty); 7836 NumRegsLeft -= std::min(NumRegs, NumRegsLeft); 7837 } 7838 7839 return ArgInfo; 7840 } 7841 7842 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo { 7843 public: 7844 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT) 7845 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {} 7846 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 7847 CodeGen::CodeGenModule &M) const override; 7848 unsigned getOpenCLKernelCallingConv() const override; 7849 7850 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM, 7851 llvm::PointerType *T, QualType QT) const override; 7852 7853 LangAS getASTAllocaAddressSpace() const override { 7854 return getLangASFromTargetAS( 7855 getABIInfo().getDataLayout().getAllocaAddrSpace()); 7856 } 7857 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM, 7858 const VarDecl *D) const override; 7859 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts, 7860 SyncScope Scope, 7861 llvm::AtomicOrdering Ordering, 7862 llvm::LLVMContext &Ctx) const override; 7863 llvm::Function * 7864 createEnqueuedBlockKernel(CodeGenFunction &CGF, 7865 llvm::Function *BlockInvokeFunc, 7866 llvm::Value *BlockLiteral) const override; 7867 bool shouldEmitStaticExternCAliases() const override; 7868 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override; 7869 }; 7870 } 7871 7872 static bool requiresAMDGPUProtectedVisibility(const Decl *D, 7873 llvm::GlobalValue *GV) { 7874 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility) 7875 return false; 7876 7877 return D->hasAttr<OpenCLKernelAttr>() || 7878 (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) || 7879 (isa<VarDecl>(D) && 7880 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())); 7881 } 7882 7883 void AMDGPUTargetCodeGenInfo::setTargetAttributes( 7884 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const { 7885 if (requiresAMDGPUProtectedVisibility(D, GV)) { 7886 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 7887 GV->setDSOLocal(true); 7888 } 7889 7890 if (GV->isDeclaration()) 7891 return; 7892 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D); 7893 if (!FD) 7894 return; 7895 7896 llvm::Function *F = cast<llvm::Function>(GV); 7897 7898 const auto *ReqdWGS = M.getLangOpts().OpenCL ? 7899 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr; 7900 7901 if (((M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>()) || 7902 (M.getLangOpts().HIP && FD->hasAttr<CUDAGlobalAttr>())) && 7903 (M.getTriple().getOS() == llvm::Triple::AMDHSA)) 7904 F->addFnAttr("amdgpu-implicitarg-num-bytes", "48"); 7905 7906 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>(); 7907 if (ReqdWGS || FlatWGS) { 7908 unsigned Min = 0; 7909 unsigned Max = 0; 7910 if (FlatWGS) { 7911 Min = FlatWGS->getMin() 7912 ->EvaluateKnownConstInt(M.getContext()) 7913 .getExtValue(); 7914 Max = FlatWGS->getMax() 7915 ->EvaluateKnownConstInt(M.getContext()) 7916 .getExtValue(); 7917 } 7918 if (ReqdWGS && Min == 0 && Max == 0) 7919 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim(); 7920 7921 if (Min != 0) { 7922 assert(Min <= Max && "Min must be less than or equal Max"); 7923 7924 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max); 7925 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal); 7926 } else 7927 assert(Max == 0 && "Max must be zero"); 7928 } 7929 7930 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) { 7931 unsigned Min = 7932 Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue(); 7933 unsigned Max = Attr->getMax() ? Attr->getMax() 7934 ->EvaluateKnownConstInt(M.getContext()) 7935 .getExtValue() 7936 : 0; 7937 7938 if (Min != 0) { 7939 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max"); 7940 7941 std::string AttrVal = llvm::utostr(Min); 7942 if (Max != 0) 7943 AttrVal = AttrVal + "," + llvm::utostr(Max); 7944 F->addFnAttr("amdgpu-waves-per-eu", AttrVal); 7945 } else 7946 assert(Max == 0 && "Max must be zero"); 7947 } 7948 7949 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) { 7950 unsigned NumSGPR = Attr->getNumSGPR(); 7951 7952 if (NumSGPR != 0) 7953 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR)); 7954 } 7955 7956 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) { 7957 uint32_t NumVGPR = Attr->getNumVGPR(); 7958 7959 if (NumVGPR != 0) 7960 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR)); 7961 } 7962 } 7963 7964 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 7965 return llvm::CallingConv::AMDGPU_KERNEL; 7966 } 7967 7968 // Currently LLVM assumes null pointers always have value 0, 7969 // which results in incorrectly transformed IR. Therefore, instead of 7970 // emitting null pointers in private and local address spaces, a null 7971 // pointer in generic address space is emitted which is casted to a 7972 // pointer in local or private address space. 7973 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer( 7974 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT, 7975 QualType QT) const { 7976 if (CGM.getContext().getTargetNullPointerValue(QT) == 0) 7977 return llvm::ConstantPointerNull::get(PT); 7978 7979 auto &Ctx = CGM.getContext(); 7980 auto NPT = llvm::PointerType::get(PT->getElementType(), 7981 Ctx.getTargetAddressSpace(LangAS::opencl_generic)); 7982 return llvm::ConstantExpr::getAddrSpaceCast( 7983 llvm::ConstantPointerNull::get(NPT), PT); 7984 } 7985 7986 LangAS 7987 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM, 7988 const VarDecl *D) const { 7989 assert(!CGM.getLangOpts().OpenCL && 7990 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) && 7991 "Address space agnostic languages only"); 7992 LangAS DefaultGlobalAS = getLangASFromTargetAS( 7993 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global)); 7994 if (!D) 7995 return DefaultGlobalAS; 7996 7997 LangAS AddrSpace = D->getType().getAddressSpace(); 7998 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace)); 7999 if (AddrSpace != LangAS::Default) 8000 return AddrSpace; 8001 8002 if (CGM.isTypeConstant(D->getType(), false)) { 8003 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace()) 8004 return ConstAS.getValue(); 8005 } 8006 return DefaultGlobalAS; 8007 } 8008 8009 llvm::SyncScope::ID 8010 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts, 8011 SyncScope Scope, 8012 llvm::AtomicOrdering Ordering, 8013 llvm::LLVMContext &Ctx) const { 8014 std::string Name; 8015 switch (Scope) { 8016 case SyncScope::OpenCLWorkGroup: 8017 Name = "workgroup"; 8018 break; 8019 case SyncScope::OpenCLDevice: 8020 Name = "agent"; 8021 break; 8022 case SyncScope::OpenCLAllSVMDevices: 8023 Name = ""; 8024 break; 8025 case SyncScope::OpenCLSubGroup: 8026 Name = "wavefront"; 8027 } 8028 8029 if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) { 8030 if (!Name.empty()) 8031 Name = Twine(Twine(Name) + Twine("-")).str(); 8032 8033 Name = Twine(Twine(Name) + Twine("one-as")).str(); 8034 } 8035 8036 return Ctx.getOrInsertSyncScopeID(Name); 8037 } 8038 8039 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const { 8040 return false; 8041 } 8042 8043 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention( 8044 const FunctionType *&FT) const { 8045 FT = getABIInfo().getContext().adjustFunctionType( 8046 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel)); 8047 } 8048 8049 //===----------------------------------------------------------------------===// 8050 // SPARC v8 ABI Implementation. 8051 // Based on the SPARC Compliance Definition version 2.4.1. 8052 // 8053 // Ensures that complex values are passed in registers. 8054 // 8055 namespace { 8056 class SparcV8ABIInfo : public DefaultABIInfo { 8057 public: 8058 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8059 8060 private: 8061 ABIArgInfo classifyReturnType(QualType RetTy) const; 8062 void computeInfo(CGFunctionInfo &FI) const override; 8063 }; 8064 } // end anonymous namespace 8065 8066 8067 ABIArgInfo 8068 SparcV8ABIInfo::classifyReturnType(QualType Ty) const { 8069 if (Ty->isAnyComplexType()) { 8070 return ABIArgInfo::getDirect(); 8071 } 8072 else { 8073 return DefaultABIInfo::classifyReturnType(Ty); 8074 } 8075 } 8076 8077 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const { 8078 8079 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8080 for (auto &Arg : FI.arguments()) 8081 Arg.info = classifyArgumentType(Arg.type); 8082 } 8083 8084 namespace { 8085 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo { 8086 public: 8087 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT) 8088 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {} 8089 }; 8090 } // end anonymous namespace 8091 8092 //===----------------------------------------------------------------------===// 8093 // SPARC v9 ABI Implementation. 8094 // Based on the SPARC Compliance Definition version 2.4.1. 8095 // 8096 // Function arguments a mapped to a nominal "parameter array" and promoted to 8097 // registers depending on their type. Each argument occupies 8 or 16 bytes in 8098 // the array, structs larger than 16 bytes are passed indirectly. 8099 // 8100 // One case requires special care: 8101 // 8102 // struct mixed { 8103 // int i; 8104 // float f; 8105 // }; 8106 // 8107 // When a struct mixed is passed by value, it only occupies 8 bytes in the 8108 // parameter array, but the int is passed in an integer register, and the float 8109 // is passed in a floating point register. This is represented as two arguments 8110 // with the LLVM IR inreg attribute: 8111 // 8112 // declare void f(i32 inreg %i, float inreg %f) 8113 // 8114 // The code generator will only allocate 4 bytes from the parameter array for 8115 // the inreg arguments. All other arguments are allocated a multiple of 8 8116 // bytes. 8117 // 8118 namespace { 8119 class SparcV9ABIInfo : public ABIInfo { 8120 public: 8121 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {} 8122 8123 private: 8124 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const; 8125 void computeInfo(CGFunctionInfo &FI) const override; 8126 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8127 QualType Ty) const override; 8128 8129 // Coercion type builder for structs passed in registers. The coercion type 8130 // serves two purposes: 8131 // 8132 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned' 8133 // in registers. 8134 // 2. Expose aligned floating point elements as first-level elements, so the 8135 // code generator knows to pass them in floating point registers. 8136 // 8137 // We also compute the InReg flag which indicates that the struct contains 8138 // aligned 32-bit floats. 8139 // 8140 struct CoerceBuilder { 8141 llvm::LLVMContext &Context; 8142 const llvm::DataLayout &DL; 8143 SmallVector<llvm::Type*, 8> Elems; 8144 uint64_t Size; 8145 bool InReg; 8146 8147 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl) 8148 : Context(c), DL(dl), Size(0), InReg(false) {} 8149 8150 // Pad Elems with integers until Size is ToSize. 8151 void pad(uint64_t ToSize) { 8152 assert(ToSize >= Size && "Cannot remove elements"); 8153 if (ToSize == Size) 8154 return; 8155 8156 // Finish the current 64-bit word. 8157 uint64_t Aligned = llvm::alignTo(Size, 64); 8158 if (Aligned > Size && Aligned <= ToSize) { 8159 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size)); 8160 Size = Aligned; 8161 } 8162 8163 // Add whole 64-bit words. 8164 while (Size + 64 <= ToSize) { 8165 Elems.push_back(llvm::Type::getInt64Ty(Context)); 8166 Size += 64; 8167 } 8168 8169 // Final in-word padding. 8170 if (Size < ToSize) { 8171 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size)); 8172 Size = ToSize; 8173 } 8174 } 8175 8176 // Add a floating point element at Offset. 8177 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) { 8178 // Unaligned floats are treated as integers. 8179 if (Offset % Bits) 8180 return; 8181 // The InReg flag is only required if there are any floats < 64 bits. 8182 if (Bits < 64) 8183 InReg = true; 8184 pad(Offset); 8185 Elems.push_back(Ty); 8186 Size = Offset + Bits; 8187 } 8188 8189 // Add a struct type to the coercion type, starting at Offset (in bits). 8190 void addStruct(uint64_t Offset, llvm::StructType *StrTy) { 8191 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy); 8192 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) { 8193 llvm::Type *ElemTy = StrTy->getElementType(i); 8194 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i); 8195 switch (ElemTy->getTypeID()) { 8196 case llvm::Type::StructTyID: 8197 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy)); 8198 break; 8199 case llvm::Type::FloatTyID: 8200 addFloat(ElemOffset, ElemTy, 32); 8201 break; 8202 case llvm::Type::DoubleTyID: 8203 addFloat(ElemOffset, ElemTy, 64); 8204 break; 8205 case llvm::Type::FP128TyID: 8206 addFloat(ElemOffset, ElemTy, 128); 8207 break; 8208 case llvm::Type::PointerTyID: 8209 if (ElemOffset % 64 == 0) { 8210 pad(ElemOffset); 8211 Elems.push_back(ElemTy); 8212 Size += 64; 8213 } 8214 break; 8215 default: 8216 break; 8217 } 8218 } 8219 } 8220 8221 // Check if Ty is a usable substitute for the coercion type. 8222 bool isUsableType(llvm::StructType *Ty) const { 8223 return llvm::makeArrayRef(Elems) == Ty->elements(); 8224 } 8225 8226 // Get the coercion type as a literal struct type. 8227 llvm::Type *getType() const { 8228 if (Elems.size() == 1) 8229 return Elems.front(); 8230 else 8231 return llvm::StructType::get(Context, Elems); 8232 } 8233 }; 8234 }; 8235 } // end anonymous namespace 8236 8237 ABIArgInfo 8238 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const { 8239 if (Ty->isVoidType()) 8240 return ABIArgInfo::getIgnore(); 8241 8242 uint64_t Size = getContext().getTypeSize(Ty); 8243 8244 // Anything too big to fit in registers is passed with an explicit indirect 8245 // pointer / sret pointer. 8246 if (Size > SizeLimit) 8247 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 8248 8249 // Treat an enum type as its underlying type. 8250 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 8251 Ty = EnumTy->getDecl()->getIntegerType(); 8252 8253 // Integer types smaller than a register are extended. 8254 if (Size < 64 && Ty->isIntegerType()) 8255 return ABIArgInfo::getExtend(Ty); 8256 8257 // Other non-aggregates go in registers. 8258 if (!isAggregateTypeForABI(Ty)) 8259 return ABIArgInfo::getDirect(); 8260 8261 // If a C++ object has either a non-trivial copy constructor or a non-trivial 8262 // destructor, it is passed with an explicit indirect pointer / sret pointer. 8263 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) 8264 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory); 8265 8266 // This is a small aggregate type that should be passed in registers. 8267 // Build a coercion type from the LLVM struct type. 8268 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty)); 8269 if (!StrTy) 8270 return ABIArgInfo::getDirect(); 8271 8272 CoerceBuilder CB(getVMContext(), getDataLayout()); 8273 CB.addStruct(0, StrTy); 8274 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64)); 8275 8276 // Try to use the original type for coercion. 8277 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType(); 8278 8279 if (CB.InReg) 8280 return ABIArgInfo::getDirectInReg(CoerceTy); 8281 else 8282 return ABIArgInfo::getDirect(CoerceTy); 8283 } 8284 8285 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8286 QualType Ty) const { 8287 ABIArgInfo AI = classifyType(Ty, 16 * 8); 8288 llvm::Type *ArgTy = CGT.ConvertType(Ty); 8289 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 8290 AI.setCoerceToType(ArgTy); 8291 8292 CharUnits SlotSize = CharUnits::fromQuantity(8); 8293 8294 CGBuilderTy &Builder = CGF.Builder; 8295 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize); 8296 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 8297 8298 auto TypeInfo = getContext().getTypeInfoInChars(Ty); 8299 8300 Address ArgAddr = Address::invalid(); 8301 CharUnits Stride; 8302 switch (AI.getKind()) { 8303 case ABIArgInfo::Expand: 8304 case ABIArgInfo::CoerceAndExpand: 8305 case ABIArgInfo::InAlloca: 8306 llvm_unreachable("Unsupported ABI kind for va_arg"); 8307 8308 case ABIArgInfo::Extend: { 8309 Stride = SlotSize; 8310 CharUnits Offset = SlotSize - TypeInfo.first; 8311 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend"); 8312 break; 8313 } 8314 8315 case ABIArgInfo::Direct: { 8316 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType()); 8317 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize); 8318 ArgAddr = Addr; 8319 break; 8320 } 8321 8322 case ABIArgInfo::Indirect: 8323 Stride = SlotSize; 8324 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect"); 8325 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"), 8326 TypeInfo.second); 8327 break; 8328 8329 case ABIArgInfo::Ignore: 8330 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second); 8331 } 8332 8333 // Update VAList. 8334 Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next"); 8335 Builder.CreateStore(NextPtr.getPointer(), VAListAddr); 8336 8337 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr"); 8338 } 8339 8340 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const { 8341 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8); 8342 for (auto &I : FI.arguments()) 8343 I.info = classifyType(I.type, 16 * 8); 8344 } 8345 8346 namespace { 8347 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo { 8348 public: 8349 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT) 8350 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {} 8351 8352 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override { 8353 return 14; 8354 } 8355 8356 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 8357 llvm::Value *Address) const override; 8358 }; 8359 } // end anonymous namespace 8360 8361 bool 8362 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF, 8363 llvm::Value *Address) const { 8364 // This is calculated from the LLVM and GCC tables and verified 8365 // against gcc output. AFAIK all ABIs use the same encoding. 8366 8367 CodeGen::CGBuilderTy &Builder = CGF.Builder; 8368 8369 llvm::IntegerType *i8 = CGF.Int8Ty; 8370 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4); 8371 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8); 8372 8373 // 0-31: the 8-byte general-purpose registers 8374 AssignToArrayRange(Builder, Address, Eight8, 0, 31); 8375 8376 // 32-63: f0-31, the 4-byte floating-point registers 8377 AssignToArrayRange(Builder, Address, Four8, 32, 63); 8378 8379 // Y = 64 8380 // PSR = 65 8381 // WIM = 66 8382 // TBR = 67 8383 // PC = 68 8384 // NPC = 69 8385 // FSR = 70 8386 // CSR = 71 8387 AssignToArrayRange(Builder, Address, Eight8, 64, 71); 8388 8389 // 72-87: d0-15, the 8-byte floating-point registers 8390 AssignToArrayRange(Builder, Address, Eight8, 72, 87); 8391 8392 return false; 8393 } 8394 8395 // ARC ABI implementation. 8396 namespace { 8397 8398 class ARCABIInfo : public DefaultABIInfo { 8399 public: 8400 using DefaultABIInfo::DefaultABIInfo; 8401 8402 private: 8403 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8404 QualType Ty) const override; 8405 8406 void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const { 8407 if (!State.FreeRegs) 8408 return; 8409 if (Info.isIndirect() && Info.getInReg()) 8410 State.FreeRegs--; 8411 else if (Info.isDirect() && Info.getInReg()) { 8412 unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32; 8413 if (sz < State.FreeRegs) 8414 State.FreeRegs -= sz; 8415 else 8416 State.FreeRegs = 0; 8417 } 8418 } 8419 8420 void computeInfo(CGFunctionInfo &FI) const override { 8421 CCState State(FI.getCallingConvention()); 8422 // ARC uses 8 registers to pass arguments. 8423 State.FreeRegs = 8; 8424 8425 if (!getCXXABI().classifyReturnType(FI)) 8426 FI.getReturnInfo() = classifyReturnType(FI.getReturnType()); 8427 updateState(FI.getReturnInfo(), FI.getReturnType(), State); 8428 for (auto &I : FI.arguments()) { 8429 I.info = classifyArgumentType(I.type, State.FreeRegs); 8430 updateState(I.info, I.type, State); 8431 } 8432 } 8433 8434 ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const; 8435 ABIArgInfo getIndirectByValue(QualType Ty) const; 8436 ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const; 8437 ABIArgInfo classifyReturnType(QualType RetTy) const; 8438 }; 8439 8440 class ARCTargetCodeGenInfo : public TargetCodeGenInfo { 8441 public: 8442 ARCTargetCodeGenInfo(CodeGenTypes &CGT) 8443 : TargetCodeGenInfo(new ARCABIInfo(CGT)) {} 8444 }; 8445 8446 8447 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const { 8448 return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) : 8449 getNaturalAlignIndirect(Ty, false); 8450 } 8451 8452 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const { 8453 // Compute the byval alignment. 8454 const unsigned MinABIStackAlignInBytes = 4; 8455 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8; 8456 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true, 8457 TypeAlign > MinABIStackAlignInBytes); 8458 } 8459 8460 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8461 QualType Ty) const { 8462 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false, 8463 getContext().getTypeInfoInChars(Ty), 8464 CharUnits::fromQuantity(4), true); 8465 } 8466 8467 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty, 8468 uint8_t FreeRegs) const { 8469 // Handle the generic C++ ABI. 8470 const RecordType *RT = Ty->getAs<RecordType>(); 8471 if (RT) { 8472 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()); 8473 if (RAA == CGCXXABI::RAA_Indirect) 8474 return getIndirectByRef(Ty, FreeRegs > 0); 8475 8476 if (RAA == CGCXXABI::RAA_DirectInMemory) 8477 return getIndirectByValue(Ty); 8478 } 8479 8480 // Treat an enum type as its underlying type. 8481 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 8482 Ty = EnumTy->getDecl()->getIntegerType(); 8483 8484 auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32; 8485 8486 if (isAggregateTypeForABI(Ty)) { 8487 // Structures with flexible arrays are always indirect. 8488 if (RT && RT->getDecl()->hasFlexibleArrayMember()) 8489 return getIndirectByValue(Ty); 8490 8491 // Ignore empty structs/unions. 8492 if (isEmptyRecord(getContext(), Ty, true)) 8493 return ABIArgInfo::getIgnore(); 8494 8495 llvm::LLVMContext &LLVMContext = getVMContext(); 8496 8497 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext); 8498 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32); 8499 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements); 8500 8501 return FreeRegs >= SizeInRegs ? 8502 ABIArgInfo::getDirectInReg(Result) : 8503 ABIArgInfo::getDirect(Result, 0, nullptr, false); 8504 } 8505 8506 return Ty->isPromotableIntegerType() ? 8507 (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) : 8508 ABIArgInfo::getExtend(Ty)) : 8509 (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() : 8510 ABIArgInfo::getDirect()); 8511 } 8512 8513 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const { 8514 if (RetTy->isAnyComplexType()) 8515 return ABIArgInfo::getDirectInReg(); 8516 8517 // Arguments of size > 4 registers are indirect. 8518 auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32; 8519 if (RetSize > 4) 8520 return getIndirectByRef(RetTy, /*HasFreeRegs*/ true); 8521 8522 return DefaultABIInfo::classifyReturnType(RetTy); 8523 } 8524 8525 } // End anonymous namespace. 8526 8527 //===----------------------------------------------------------------------===// 8528 // XCore ABI Implementation 8529 //===----------------------------------------------------------------------===// 8530 8531 namespace { 8532 8533 /// A SmallStringEnc instance is used to build up the TypeString by passing 8534 /// it by reference between functions that append to it. 8535 typedef llvm::SmallString<128> SmallStringEnc; 8536 8537 /// TypeStringCache caches the meta encodings of Types. 8538 /// 8539 /// The reason for caching TypeStrings is two fold: 8540 /// 1. To cache a type's encoding for later uses; 8541 /// 2. As a means to break recursive member type inclusion. 8542 /// 8543 /// A cache Entry can have a Status of: 8544 /// NonRecursive: The type encoding is not recursive; 8545 /// Recursive: The type encoding is recursive; 8546 /// Incomplete: An incomplete TypeString; 8547 /// IncompleteUsed: An incomplete TypeString that has been used in a 8548 /// Recursive type encoding. 8549 /// 8550 /// A NonRecursive entry will have all of its sub-members expanded as fully 8551 /// as possible. Whilst it may contain types which are recursive, the type 8552 /// itself is not recursive and thus its encoding may be safely used whenever 8553 /// the type is encountered. 8554 /// 8555 /// A Recursive entry will have all of its sub-members expanded as fully as 8556 /// possible. The type itself is recursive and it may contain other types which 8557 /// are recursive. The Recursive encoding must not be used during the expansion 8558 /// of a recursive type's recursive branch. For simplicity the code uses 8559 /// IncompleteCount to reject all usage of Recursive encodings for member types. 8560 /// 8561 /// An Incomplete entry is always a RecordType and only encodes its 8562 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and 8563 /// are placed into the cache during type expansion as a means to identify and 8564 /// handle recursive inclusion of types as sub-members. If there is recursion 8565 /// the entry becomes IncompleteUsed. 8566 /// 8567 /// During the expansion of a RecordType's members: 8568 /// 8569 /// If the cache contains a NonRecursive encoding for the member type, the 8570 /// cached encoding is used; 8571 /// 8572 /// If the cache contains a Recursive encoding for the member type, the 8573 /// cached encoding is 'Swapped' out, as it may be incorrect, and... 8574 /// 8575 /// If the member is a RecordType, an Incomplete encoding is placed into the 8576 /// cache to break potential recursive inclusion of itself as a sub-member; 8577 /// 8578 /// Once a member RecordType has been expanded, its temporary incomplete 8579 /// entry is removed from the cache. If a Recursive encoding was swapped out 8580 /// it is swapped back in; 8581 /// 8582 /// If an incomplete entry is used to expand a sub-member, the incomplete 8583 /// entry is marked as IncompleteUsed. The cache keeps count of how many 8584 /// IncompleteUsed entries it currently contains in IncompleteUsedCount; 8585 /// 8586 /// If a member's encoding is found to be a NonRecursive or Recursive viz: 8587 /// IncompleteUsedCount==0, the member's encoding is added to the cache. 8588 /// Else the member is part of a recursive type and thus the recursion has 8589 /// been exited too soon for the encoding to be correct for the member. 8590 /// 8591 class TypeStringCache { 8592 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed}; 8593 struct Entry { 8594 std::string Str; // The encoded TypeString for the type. 8595 enum Status State; // Information about the encoding in 'Str'. 8596 std::string Swapped; // A temporary place holder for a Recursive encoding 8597 // during the expansion of RecordType's members. 8598 }; 8599 std::map<const IdentifierInfo *, struct Entry> Map; 8600 unsigned IncompleteCount; // Number of Incomplete entries in the Map. 8601 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map. 8602 public: 8603 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {} 8604 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc); 8605 bool removeIncomplete(const IdentifierInfo *ID); 8606 void addIfComplete(const IdentifierInfo *ID, StringRef Str, 8607 bool IsRecursive); 8608 StringRef lookupStr(const IdentifierInfo *ID); 8609 }; 8610 8611 /// TypeString encodings for enum & union fields must be order. 8612 /// FieldEncoding is a helper for this ordering process. 8613 class FieldEncoding { 8614 bool HasName; 8615 std::string Enc; 8616 public: 8617 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {} 8618 StringRef str() { return Enc; } 8619 bool operator<(const FieldEncoding &rhs) const { 8620 if (HasName != rhs.HasName) return HasName; 8621 return Enc < rhs.Enc; 8622 } 8623 }; 8624 8625 class XCoreABIInfo : public DefaultABIInfo { 8626 public: 8627 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {} 8628 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8629 QualType Ty) const override; 8630 }; 8631 8632 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo { 8633 mutable TypeStringCache TSC; 8634 public: 8635 XCoreTargetCodeGenInfo(CodeGenTypes &CGT) 8636 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {} 8637 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV, 8638 CodeGen::CodeGenModule &M) const override; 8639 }; 8640 8641 } // End anonymous namespace. 8642 8643 // TODO: this implementation is likely now redundant with the default 8644 // EmitVAArg. 8645 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 8646 QualType Ty) const { 8647 CGBuilderTy &Builder = CGF.Builder; 8648 8649 // Get the VAList. 8650 CharUnits SlotSize = CharUnits::fromQuantity(4); 8651 Address AP(Builder.CreateLoad(VAListAddr), SlotSize); 8652 8653 // Handle the argument. 8654 ABIArgInfo AI = classifyArgumentType(Ty); 8655 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty); 8656 llvm::Type *ArgTy = CGT.ConvertType(Ty); 8657 if (AI.canHaveCoerceToType() && !AI.getCoerceToType()) 8658 AI.setCoerceToType(ArgTy); 8659 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy); 8660 8661 Address Val = Address::invalid(); 8662 CharUnits ArgSize = CharUnits::Zero(); 8663 switch (AI.getKind()) { 8664 case ABIArgInfo::Expand: 8665 case ABIArgInfo::CoerceAndExpand: 8666 case ABIArgInfo::InAlloca: 8667 llvm_unreachable("Unsupported ABI kind for va_arg"); 8668 case ABIArgInfo::Ignore: 8669 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign); 8670 ArgSize = CharUnits::Zero(); 8671 break; 8672 case ABIArgInfo::Extend: 8673 case ABIArgInfo::Direct: 8674 Val = Builder.CreateBitCast(AP, ArgPtrTy); 8675 ArgSize = CharUnits::fromQuantity( 8676 getDataLayout().getTypeAllocSize(AI.getCoerceToType())); 8677 ArgSize = ArgSize.alignTo(SlotSize); 8678 break; 8679 case ABIArgInfo::Indirect: 8680 Val = Builder.CreateElementBitCast(AP, ArgPtrTy); 8681 Val = Address(Builder.CreateLoad(Val), TypeAlign); 8682 ArgSize = SlotSize; 8683 break; 8684 } 8685 8686 // Increment the VAList. 8687 if (!ArgSize.isZero()) { 8688 Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize); 8689 Builder.CreateStore(APN.getPointer(), VAListAddr); 8690 } 8691 8692 return Val; 8693 } 8694 8695 /// During the expansion of a RecordType, an incomplete TypeString is placed 8696 /// into the cache as a means to identify and break recursion. 8697 /// If there is a Recursive encoding in the cache, it is swapped out and will 8698 /// be reinserted by removeIncomplete(). 8699 /// All other types of encoding should have been used rather than arriving here. 8700 void TypeStringCache::addIncomplete(const IdentifierInfo *ID, 8701 std::string StubEnc) { 8702 if (!ID) 8703 return; 8704 Entry &E = Map[ID]; 8705 assert( (E.Str.empty() || E.State == Recursive) && 8706 "Incorrectly use of addIncomplete"); 8707 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()"); 8708 E.Swapped.swap(E.Str); // swap out the Recursive 8709 E.Str.swap(StubEnc); 8710 E.State = Incomplete; 8711 ++IncompleteCount; 8712 } 8713 8714 /// Once the RecordType has been expanded, the temporary incomplete TypeString 8715 /// must be removed from the cache. 8716 /// If a Recursive was swapped out by addIncomplete(), it will be replaced. 8717 /// Returns true if the RecordType was defined recursively. 8718 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) { 8719 if (!ID) 8720 return false; 8721 auto I = Map.find(ID); 8722 assert(I != Map.end() && "Entry not present"); 8723 Entry &E = I->second; 8724 assert( (E.State == Incomplete || 8725 E.State == IncompleteUsed) && 8726 "Entry must be an incomplete type"); 8727 bool IsRecursive = false; 8728 if (E.State == IncompleteUsed) { 8729 // We made use of our Incomplete encoding, thus we are recursive. 8730 IsRecursive = true; 8731 --IncompleteUsedCount; 8732 } 8733 if (E.Swapped.empty()) 8734 Map.erase(I); 8735 else { 8736 // Swap the Recursive back. 8737 E.Swapped.swap(E.Str); 8738 E.Swapped.clear(); 8739 E.State = Recursive; 8740 } 8741 --IncompleteCount; 8742 return IsRecursive; 8743 } 8744 8745 /// Add the encoded TypeString to the cache only if it is NonRecursive or 8746 /// Recursive (viz: all sub-members were expanded as fully as possible). 8747 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str, 8748 bool IsRecursive) { 8749 if (!ID || IncompleteUsedCount) 8750 return; // No key or it is is an incomplete sub-type so don't add. 8751 Entry &E = Map[ID]; 8752 if (IsRecursive && !E.Str.empty()) { 8753 assert(E.State==Recursive && E.Str.size() == Str.size() && 8754 "This is not the same Recursive entry"); 8755 // The parent container was not recursive after all, so we could have used 8756 // this Recursive sub-member entry after all, but we assumed the worse when 8757 // we started viz: IncompleteCount!=0. 8758 return; 8759 } 8760 assert(E.Str.empty() && "Entry already present"); 8761 E.Str = Str.str(); 8762 E.State = IsRecursive? Recursive : NonRecursive; 8763 } 8764 8765 /// Return a cached TypeString encoding for the ID. If there isn't one, or we 8766 /// are recursively expanding a type (IncompleteCount != 0) and the cached 8767 /// encoding is Recursive, return an empty StringRef. 8768 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) { 8769 if (!ID) 8770 return StringRef(); // We have no key. 8771 auto I = Map.find(ID); 8772 if (I == Map.end()) 8773 return StringRef(); // We have no encoding. 8774 Entry &E = I->second; 8775 if (E.State == Recursive && IncompleteCount) 8776 return StringRef(); // We don't use Recursive encodings for member types. 8777 8778 if (E.State == Incomplete) { 8779 // The incomplete type is being used to break out of recursion. 8780 E.State = IncompleteUsed; 8781 ++IncompleteUsedCount; 8782 } 8783 return E.Str; 8784 } 8785 8786 /// The XCore ABI includes a type information section that communicates symbol 8787 /// type information to the linker. The linker uses this information to verify 8788 /// safety/correctness of things such as array bound and pointers et al. 8789 /// The ABI only requires C (and XC) language modules to emit TypeStrings. 8790 /// This type information (TypeString) is emitted into meta data for all global 8791 /// symbols: definitions, declarations, functions & variables. 8792 /// 8793 /// The TypeString carries type, qualifier, name, size & value details. 8794 /// Please see 'Tools Development Guide' section 2.16.2 for format details: 8795 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf 8796 /// The output is tested by test/CodeGen/xcore-stringtype.c. 8797 /// 8798 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 8799 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC); 8800 8801 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols. 8802 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV, 8803 CodeGen::CodeGenModule &CGM) const { 8804 SmallStringEnc Enc; 8805 if (getTypeString(Enc, D, CGM, TSC)) { 8806 llvm::LLVMContext &Ctx = CGM.getModule().getContext(); 8807 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV), 8808 llvm::MDString::get(Ctx, Enc.str())}; 8809 llvm::NamedMDNode *MD = 8810 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings"); 8811 MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); 8812 } 8813 } 8814 8815 //===----------------------------------------------------------------------===// 8816 // SPIR ABI Implementation 8817 //===----------------------------------------------------------------------===// 8818 8819 namespace { 8820 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo { 8821 public: 8822 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT) 8823 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {} 8824 unsigned getOpenCLKernelCallingConv() const override; 8825 }; 8826 8827 } // End anonymous namespace. 8828 8829 namespace clang { 8830 namespace CodeGen { 8831 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) { 8832 DefaultABIInfo SPIRABI(CGM.getTypes()); 8833 SPIRABI.computeInfo(FI); 8834 } 8835 } 8836 } 8837 8838 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const { 8839 return llvm::CallingConv::SPIR_KERNEL; 8840 } 8841 8842 static bool appendType(SmallStringEnc &Enc, QualType QType, 8843 const CodeGen::CodeGenModule &CGM, 8844 TypeStringCache &TSC); 8845 8846 /// Helper function for appendRecordType(). 8847 /// Builds a SmallVector containing the encoded field types in declaration 8848 /// order. 8849 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE, 8850 const RecordDecl *RD, 8851 const CodeGen::CodeGenModule &CGM, 8852 TypeStringCache &TSC) { 8853 for (const auto *Field : RD->fields()) { 8854 SmallStringEnc Enc; 8855 Enc += "m("; 8856 Enc += Field->getName(); 8857 Enc += "){"; 8858 if (Field->isBitField()) { 8859 Enc += "b("; 8860 llvm::raw_svector_ostream OS(Enc); 8861 OS << Field->getBitWidthValue(CGM.getContext()); 8862 Enc += ':'; 8863 } 8864 if (!appendType(Enc, Field->getType(), CGM, TSC)) 8865 return false; 8866 if (Field->isBitField()) 8867 Enc += ')'; 8868 Enc += '}'; 8869 FE.emplace_back(!Field->getName().empty(), Enc); 8870 } 8871 return true; 8872 } 8873 8874 /// Appends structure and union types to Enc and adds encoding to cache. 8875 /// Recursively calls appendType (via extractFieldType) for each field. 8876 /// Union types have their fields ordered according to the ABI. 8877 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT, 8878 const CodeGen::CodeGenModule &CGM, 8879 TypeStringCache &TSC, const IdentifierInfo *ID) { 8880 // Append the cached TypeString if we have one. 8881 StringRef TypeString = TSC.lookupStr(ID); 8882 if (!TypeString.empty()) { 8883 Enc += TypeString; 8884 return true; 8885 } 8886 8887 // Start to emit an incomplete TypeString. 8888 size_t Start = Enc.size(); 8889 Enc += (RT->isUnionType()? 'u' : 's'); 8890 Enc += '('; 8891 if (ID) 8892 Enc += ID->getName(); 8893 Enc += "){"; 8894 8895 // We collect all encoded fields and order as necessary. 8896 bool IsRecursive = false; 8897 const RecordDecl *RD = RT->getDecl()->getDefinition(); 8898 if (RD && !RD->field_empty()) { 8899 // An incomplete TypeString stub is placed in the cache for this RecordType 8900 // so that recursive calls to this RecordType will use it whilst building a 8901 // complete TypeString for this RecordType. 8902 SmallVector<FieldEncoding, 16> FE; 8903 std::string StubEnc(Enc.substr(Start).str()); 8904 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString. 8905 TSC.addIncomplete(ID, std::move(StubEnc)); 8906 if (!extractFieldType(FE, RD, CGM, TSC)) { 8907 (void) TSC.removeIncomplete(ID); 8908 return false; 8909 } 8910 IsRecursive = TSC.removeIncomplete(ID); 8911 // The ABI requires unions to be sorted but not structures. 8912 // See FieldEncoding::operator< for sort algorithm. 8913 if (RT->isUnionType()) 8914 llvm::sort(FE); 8915 // We can now complete the TypeString. 8916 unsigned E = FE.size(); 8917 for (unsigned I = 0; I != E; ++I) { 8918 if (I) 8919 Enc += ','; 8920 Enc += FE[I].str(); 8921 } 8922 } 8923 Enc += '}'; 8924 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive); 8925 return true; 8926 } 8927 8928 /// Appends enum types to Enc and adds the encoding to the cache. 8929 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET, 8930 TypeStringCache &TSC, 8931 const IdentifierInfo *ID) { 8932 // Append the cached TypeString if we have one. 8933 StringRef TypeString = TSC.lookupStr(ID); 8934 if (!TypeString.empty()) { 8935 Enc += TypeString; 8936 return true; 8937 } 8938 8939 size_t Start = Enc.size(); 8940 Enc += "e("; 8941 if (ID) 8942 Enc += ID->getName(); 8943 Enc += "){"; 8944 8945 // We collect all encoded enumerations and order them alphanumerically. 8946 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) { 8947 SmallVector<FieldEncoding, 16> FE; 8948 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E; 8949 ++I) { 8950 SmallStringEnc EnumEnc; 8951 EnumEnc += "m("; 8952 EnumEnc += I->getName(); 8953 EnumEnc += "){"; 8954 I->getInitVal().toString(EnumEnc); 8955 EnumEnc += '}'; 8956 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc)); 8957 } 8958 llvm::sort(FE); 8959 unsigned E = FE.size(); 8960 for (unsigned I = 0; I != E; ++I) { 8961 if (I) 8962 Enc += ','; 8963 Enc += FE[I].str(); 8964 } 8965 } 8966 Enc += '}'; 8967 TSC.addIfComplete(ID, Enc.substr(Start), false); 8968 return true; 8969 } 8970 8971 /// Appends type's qualifier to Enc. 8972 /// This is done prior to appending the type's encoding. 8973 static void appendQualifier(SmallStringEnc &Enc, QualType QT) { 8974 // Qualifiers are emitted in alphabetical order. 8975 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"}; 8976 int Lookup = 0; 8977 if (QT.isConstQualified()) 8978 Lookup += 1<<0; 8979 if (QT.isRestrictQualified()) 8980 Lookup += 1<<1; 8981 if (QT.isVolatileQualified()) 8982 Lookup += 1<<2; 8983 Enc += Table[Lookup]; 8984 } 8985 8986 /// Appends built-in types to Enc. 8987 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) { 8988 const char *EncType; 8989 switch (BT->getKind()) { 8990 case BuiltinType::Void: 8991 EncType = "0"; 8992 break; 8993 case BuiltinType::Bool: 8994 EncType = "b"; 8995 break; 8996 case BuiltinType::Char_U: 8997 EncType = "uc"; 8998 break; 8999 case BuiltinType::UChar: 9000 EncType = "uc"; 9001 break; 9002 case BuiltinType::SChar: 9003 EncType = "sc"; 9004 break; 9005 case BuiltinType::UShort: 9006 EncType = "us"; 9007 break; 9008 case BuiltinType::Short: 9009 EncType = "ss"; 9010 break; 9011 case BuiltinType::UInt: 9012 EncType = "ui"; 9013 break; 9014 case BuiltinType::Int: 9015 EncType = "si"; 9016 break; 9017 case BuiltinType::ULong: 9018 EncType = "ul"; 9019 break; 9020 case BuiltinType::Long: 9021 EncType = "sl"; 9022 break; 9023 case BuiltinType::ULongLong: 9024 EncType = "ull"; 9025 break; 9026 case BuiltinType::LongLong: 9027 EncType = "sll"; 9028 break; 9029 case BuiltinType::Float: 9030 EncType = "ft"; 9031 break; 9032 case BuiltinType::Double: 9033 EncType = "d"; 9034 break; 9035 case BuiltinType::LongDouble: 9036 EncType = "ld"; 9037 break; 9038 default: 9039 return false; 9040 } 9041 Enc += EncType; 9042 return true; 9043 } 9044 9045 /// Appends a pointer encoding to Enc before calling appendType for the pointee. 9046 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT, 9047 const CodeGen::CodeGenModule &CGM, 9048 TypeStringCache &TSC) { 9049 Enc += "p("; 9050 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC)) 9051 return false; 9052 Enc += ')'; 9053 return true; 9054 } 9055 9056 /// Appends array encoding to Enc before calling appendType for the element. 9057 static bool appendArrayType(SmallStringEnc &Enc, QualType QT, 9058 const ArrayType *AT, 9059 const CodeGen::CodeGenModule &CGM, 9060 TypeStringCache &TSC, StringRef NoSizeEnc) { 9061 if (AT->getSizeModifier() != ArrayType::Normal) 9062 return false; 9063 Enc += "a("; 9064 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 9065 CAT->getSize().toStringUnsigned(Enc); 9066 else 9067 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "". 9068 Enc += ':'; 9069 // The Qualifiers should be attached to the type rather than the array. 9070 appendQualifier(Enc, QT); 9071 if (!appendType(Enc, AT->getElementType(), CGM, TSC)) 9072 return false; 9073 Enc += ')'; 9074 return true; 9075 } 9076 9077 /// Appends a function encoding to Enc, calling appendType for the return type 9078 /// and the arguments. 9079 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT, 9080 const CodeGen::CodeGenModule &CGM, 9081 TypeStringCache &TSC) { 9082 Enc += "f{"; 9083 if (!appendType(Enc, FT->getReturnType(), CGM, TSC)) 9084 return false; 9085 Enc += "}("; 9086 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) { 9087 // N.B. we are only interested in the adjusted param types. 9088 auto I = FPT->param_type_begin(); 9089 auto E = FPT->param_type_end(); 9090 if (I != E) { 9091 do { 9092 if (!appendType(Enc, *I, CGM, TSC)) 9093 return false; 9094 ++I; 9095 if (I != E) 9096 Enc += ','; 9097 } while (I != E); 9098 if (FPT->isVariadic()) 9099 Enc += ",va"; 9100 } else { 9101 if (FPT->isVariadic()) 9102 Enc += "va"; 9103 else 9104 Enc += '0'; 9105 } 9106 } 9107 Enc += ')'; 9108 return true; 9109 } 9110 9111 /// Handles the type's qualifier before dispatching a call to handle specific 9112 /// type encodings. 9113 static bool appendType(SmallStringEnc &Enc, QualType QType, 9114 const CodeGen::CodeGenModule &CGM, 9115 TypeStringCache &TSC) { 9116 9117 QualType QT = QType.getCanonicalType(); 9118 9119 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) 9120 // The Qualifiers should be attached to the type rather than the array. 9121 // Thus we don't call appendQualifier() here. 9122 return appendArrayType(Enc, QT, AT, CGM, TSC, ""); 9123 9124 appendQualifier(Enc, QT); 9125 9126 if (const BuiltinType *BT = QT->getAs<BuiltinType>()) 9127 return appendBuiltinType(Enc, BT); 9128 9129 if (const PointerType *PT = QT->getAs<PointerType>()) 9130 return appendPointerType(Enc, PT, CGM, TSC); 9131 9132 if (const EnumType *ET = QT->getAs<EnumType>()) 9133 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier()); 9134 9135 if (const RecordType *RT = QT->getAsStructureType()) 9136 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 9137 9138 if (const RecordType *RT = QT->getAsUnionType()) 9139 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier()); 9140 9141 if (const FunctionType *FT = QT->getAs<FunctionType>()) 9142 return appendFunctionType(Enc, FT, CGM, TSC); 9143 9144 return false; 9145 } 9146 9147 static bool getTypeString(SmallStringEnc &Enc, const Decl *D, 9148 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) { 9149 if (!D) 9150 return false; 9151 9152 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 9153 if (FD->getLanguageLinkage() != CLanguageLinkage) 9154 return false; 9155 return appendType(Enc, FD->getType(), CGM, TSC); 9156 } 9157 9158 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 9159 if (VD->getLanguageLinkage() != CLanguageLinkage) 9160 return false; 9161 QualType QT = VD->getType().getCanonicalType(); 9162 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) { 9163 // Global ArrayTypes are given a size of '*' if the size is unknown. 9164 // The Qualifiers should be attached to the type rather than the array. 9165 // Thus we don't call appendQualifier() here. 9166 return appendArrayType(Enc, QT, AT, CGM, TSC, "*"); 9167 } 9168 return appendType(Enc, QT, CGM, TSC); 9169 } 9170 return false; 9171 } 9172 9173 //===----------------------------------------------------------------------===// 9174 // RISCV ABI Implementation 9175 //===----------------------------------------------------------------------===// 9176 9177 namespace { 9178 class RISCVABIInfo : public DefaultABIInfo { 9179 private: 9180 unsigned XLen; // Size of the integer ('x') registers in bits. 9181 static const int NumArgGPRs = 8; 9182 9183 public: 9184 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen) 9185 : DefaultABIInfo(CGT), XLen(XLen) {} 9186 9187 // DefaultABIInfo's classifyReturnType and classifyArgumentType are 9188 // non-virtual, but computeInfo is virtual, so we overload it. 9189 void computeInfo(CGFunctionInfo &FI) const override; 9190 9191 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, 9192 int &ArgGPRsLeft) const; 9193 ABIArgInfo classifyReturnType(QualType RetTy) const; 9194 9195 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9196 QualType Ty) const override; 9197 9198 ABIArgInfo extendType(QualType Ty) const; 9199 }; 9200 } // end anonymous namespace 9201 9202 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const { 9203 QualType RetTy = FI.getReturnType(); 9204 if (!getCXXABI().classifyReturnType(FI)) 9205 FI.getReturnInfo() = classifyReturnType(RetTy); 9206 9207 // IsRetIndirect is true if classifyArgumentType indicated the value should 9208 // be passed indirect or if the type size is greater than 2*xlen. e.g. fp128 9209 // is passed direct in LLVM IR, relying on the backend lowering code to 9210 // rewrite the argument list and pass indirectly on RV32. 9211 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect || 9212 getContext().getTypeSize(RetTy) > (2 * XLen); 9213 9214 // We must track the number of GPRs used in order to conform to the RISC-V 9215 // ABI, as integer scalars passed in registers should have signext/zeroext 9216 // when promoted, but are anyext if passed on the stack. As GPR usage is 9217 // different for variadic arguments, we must also track whether we are 9218 // examining a vararg or not. 9219 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs; 9220 int NumFixedArgs = FI.getNumRequiredArgs(); 9221 9222 int ArgNum = 0; 9223 for (auto &ArgInfo : FI.arguments()) { 9224 bool IsFixed = ArgNum < NumFixedArgs; 9225 ArgInfo.info = classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft); 9226 ArgNum++; 9227 } 9228 } 9229 9230 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed, 9231 int &ArgGPRsLeft) const { 9232 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow"); 9233 Ty = useFirstFieldIfTransparentUnion(Ty); 9234 9235 // Structures with either a non-trivial destructor or a non-trivial 9236 // copy constructor are always passed indirectly. 9237 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) { 9238 if (ArgGPRsLeft) 9239 ArgGPRsLeft -= 1; 9240 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA == 9241 CGCXXABI::RAA_DirectInMemory); 9242 } 9243 9244 // Ignore empty structs/unions. 9245 if (isEmptyRecord(getContext(), Ty, true)) 9246 return ABIArgInfo::getIgnore(); 9247 9248 uint64_t Size = getContext().getTypeSize(Ty); 9249 uint64_t NeededAlign = getContext().getTypeAlign(Ty); 9250 bool MustUseStack = false; 9251 // Determine the number of GPRs needed to pass the current argument 9252 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned" 9253 // register pairs, so may consume 3 registers. 9254 int NeededArgGPRs = 1; 9255 if (!IsFixed && NeededAlign == 2 * XLen) 9256 NeededArgGPRs = 2 + (ArgGPRsLeft % 2); 9257 else if (Size > XLen && Size <= 2 * XLen) 9258 NeededArgGPRs = 2; 9259 9260 if (NeededArgGPRs > ArgGPRsLeft) { 9261 MustUseStack = true; 9262 NeededArgGPRs = ArgGPRsLeft; 9263 } 9264 9265 ArgGPRsLeft -= NeededArgGPRs; 9266 9267 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) { 9268 // Treat an enum type as its underlying type. 9269 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) 9270 Ty = EnumTy->getDecl()->getIntegerType(); 9271 9272 // All integral types are promoted to XLen width, unless passed on the 9273 // stack. 9274 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) { 9275 return extendType(Ty); 9276 } 9277 9278 return ABIArgInfo::getDirect(); 9279 } 9280 9281 // Aggregates which are <= 2*XLen will be passed in registers if possible, 9282 // so coerce to integers. 9283 if (Size <= 2 * XLen) { 9284 unsigned Alignment = getContext().getTypeAlign(Ty); 9285 9286 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is 9287 // required, and a 2-element XLen array if only XLen alignment is required. 9288 if (Size <= XLen) { 9289 return ABIArgInfo::getDirect( 9290 llvm::IntegerType::get(getVMContext(), XLen)); 9291 } else if (Alignment == 2 * XLen) { 9292 return ABIArgInfo::getDirect( 9293 llvm::IntegerType::get(getVMContext(), 2 * XLen)); 9294 } else { 9295 return ABIArgInfo::getDirect(llvm::ArrayType::get( 9296 llvm::IntegerType::get(getVMContext(), XLen), 2)); 9297 } 9298 } 9299 return getNaturalAlignIndirect(Ty, /*ByVal=*/false); 9300 } 9301 9302 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const { 9303 if (RetTy->isVoidType()) 9304 return ABIArgInfo::getIgnore(); 9305 9306 int ArgGPRsLeft = 2; 9307 9308 // The rules for return and argument types are the same, so defer to 9309 // classifyArgumentType. 9310 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft); 9311 } 9312 9313 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr, 9314 QualType Ty) const { 9315 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8); 9316 9317 // Empty records are ignored for parameter passing purposes. 9318 if (isEmptyRecord(getContext(), Ty, true)) { 9319 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize); 9320 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty)); 9321 return Addr; 9322 } 9323 9324 std::pair<CharUnits, CharUnits> SizeAndAlign = 9325 getContext().getTypeInfoInChars(Ty); 9326 9327 // Arguments bigger than 2*Xlen bytes are passed indirectly. 9328 bool IsIndirect = SizeAndAlign.first > 2 * SlotSize; 9329 9330 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign, 9331 SlotSize, /*AllowHigherAlign=*/true); 9332 } 9333 9334 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const { 9335 int TySize = getContext().getTypeSize(Ty); 9336 // RV64 ABI requires unsigned 32 bit integers to be sign extended. 9337 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32) 9338 return ABIArgInfo::getSignExtend(Ty); 9339 return ABIArgInfo::getExtend(Ty); 9340 } 9341 9342 namespace { 9343 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo { 9344 public: 9345 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen) 9346 : TargetCodeGenInfo(new RISCVABIInfo(CGT, XLen)) {} 9347 9348 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV, 9349 CodeGen::CodeGenModule &CGM) const override { 9350 const auto *FD = dyn_cast_or_null<FunctionDecl>(D); 9351 if (!FD) return; 9352 9353 const auto *Attr = FD->getAttr<RISCVInterruptAttr>(); 9354 if (!Attr) 9355 return; 9356 9357 const char *Kind; 9358 switch (Attr->getInterrupt()) { 9359 case RISCVInterruptAttr::user: Kind = "user"; break; 9360 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break; 9361 case RISCVInterruptAttr::machine: Kind = "machine"; break; 9362 } 9363 9364 auto *Fn = cast<llvm::Function>(GV); 9365 9366 Fn->addFnAttr("interrupt", Kind); 9367 } 9368 }; 9369 } // namespace 9370 9371 //===----------------------------------------------------------------------===// 9372 // Driver code 9373 //===----------------------------------------------------------------------===// 9374 9375 bool CodeGenModule::supportsCOMDAT() const { 9376 return getTriple().supportsCOMDAT(); 9377 } 9378 9379 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 9380 if (TheTargetCodeGenInfo) 9381 return *TheTargetCodeGenInfo; 9382 9383 // Helper to set the unique_ptr while still keeping the return value. 9384 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & { 9385 this->TheTargetCodeGenInfo.reset(P); 9386 return *P; 9387 }; 9388 9389 const llvm::Triple &Triple = getTarget().getTriple(); 9390 switch (Triple.getArch()) { 9391 default: 9392 return SetCGInfo(new DefaultTargetCodeGenInfo(Types)); 9393 9394 case llvm::Triple::le32: 9395 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 9396 case llvm::Triple::mips: 9397 case llvm::Triple::mipsel: 9398 if (Triple.getOS() == llvm::Triple::NaCl) 9399 return SetCGInfo(new PNaClTargetCodeGenInfo(Types)); 9400 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true)); 9401 9402 case llvm::Triple::mips64: 9403 case llvm::Triple::mips64el: 9404 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false)); 9405 9406 case llvm::Triple::avr: 9407 return SetCGInfo(new AVRTargetCodeGenInfo(Types)); 9408 9409 case llvm::Triple::aarch64: 9410 case llvm::Triple::aarch64_be: { 9411 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS; 9412 if (getTarget().getABI() == "darwinpcs") 9413 Kind = AArch64ABIInfo::DarwinPCS; 9414 else if (Triple.isOSWindows()) 9415 return SetCGInfo( 9416 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64)); 9417 9418 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind)); 9419 } 9420 9421 case llvm::Triple::wasm32: 9422 case llvm::Triple::wasm64: 9423 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types)); 9424 9425 case llvm::Triple::arm: 9426 case llvm::Triple::armeb: 9427 case llvm::Triple::thumb: 9428 case llvm::Triple::thumbeb: { 9429 if (Triple.getOS() == llvm::Triple::Win32) { 9430 return SetCGInfo( 9431 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP)); 9432 } 9433 9434 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS; 9435 StringRef ABIStr = getTarget().getABI(); 9436 if (ABIStr == "apcs-gnu") 9437 Kind = ARMABIInfo::APCS; 9438 else if (ABIStr == "aapcs16") 9439 Kind = ARMABIInfo::AAPCS16_VFP; 9440 else if (CodeGenOpts.FloatABI == "hard" || 9441 (CodeGenOpts.FloatABI != "soft" && 9442 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF || 9443 Triple.getEnvironment() == llvm::Triple::MuslEABIHF || 9444 Triple.getEnvironment() == llvm::Triple::EABIHF))) 9445 Kind = ARMABIInfo::AAPCS_VFP; 9446 9447 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind)); 9448 } 9449 9450 case llvm::Triple::ppc: 9451 return SetCGInfo( 9452 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft")); 9453 case llvm::Triple::ppc64: 9454 if (Triple.isOSBinFormatELF()) { 9455 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1; 9456 if (getTarget().getABI() == "elfv2") 9457 Kind = PPC64_SVR4_ABIInfo::ELFv2; 9458 bool HasQPX = getTarget().getABI() == "elfv1-qpx"; 9459 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 9460 9461 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX, 9462 IsSoftFloat)); 9463 } else 9464 return SetCGInfo(new PPC64TargetCodeGenInfo(Types)); 9465 case llvm::Triple::ppc64le: { 9466 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 9467 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2; 9468 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx") 9469 Kind = PPC64_SVR4_ABIInfo::ELFv1; 9470 bool HasQPX = getTarget().getABI() == "elfv1-qpx"; 9471 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 9472 9473 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX, 9474 IsSoftFloat)); 9475 } 9476 9477 case llvm::Triple::nvptx: 9478 case llvm::Triple::nvptx64: 9479 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types)); 9480 9481 case llvm::Triple::msp430: 9482 return SetCGInfo(new MSP430TargetCodeGenInfo(Types)); 9483 9484 case llvm::Triple::riscv32: 9485 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, 32)); 9486 case llvm::Triple::riscv64: 9487 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, 64)); 9488 9489 case llvm::Triple::systemz: { 9490 bool HasVector = getTarget().getABI() == "vector"; 9491 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector)); 9492 } 9493 9494 case llvm::Triple::tce: 9495 case llvm::Triple::tcele: 9496 return SetCGInfo(new TCETargetCodeGenInfo(Types)); 9497 9498 case llvm::Triple::x86: { 9499 bool IsDarwinVectorABI = Triple.isOSDarwin(); 9500 bool RetSmallStructInRegABI = 9501 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts); 9502 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); 9503 9504 if (Triple.getOS() == llvm::Triple::Win32) { 9505 return SetCGInfo(new WinX86_32TargetCodeGenInfo( 9506 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 9507 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters)); 9508 } else { 9509 bool EnableMMX = getContext().getTargetInfo().getABI() != "no-mmx"; 9510 return SetCGInfo(new X86_32TargetCodeGenInfo( 9511 Types, IsDarwinVectorABI, RetSmallStructInRegABI, 9512 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters, 9513 CodeGenOpts.FloatABI == "soft", EnableMMX)); 9514 } 9515 } 9516 9517 case llvm::Triple::x86_64: { 9518 StringRef ABI = getTarget().getABI(); 9519 X86AVXABILevel AVXLevel = 9520 (ABI == "avx512" 9521 ? X86AVXABILevel::AVX512 9522 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None); 9523 9524 switch (Triple.getOS()) { 9525 case llvm::Triple::Win32: 9526 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel)); 9527 default: 9528 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel)); 9529 } 9530 } 9531 case llvm::Triple::hexagon: 9532 return SetCGInfo(new HexagonTargetCodeGenInfo(Types)); 9533 case llvm::Triple::lanai: 9534 return SetCGInfo(new LanaiTargetCodeGenInfo(Types)); 9535 case llvm::Triple::r600: 9536 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 9537 case llvm::Triple::amdgcn: 9538 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types)); 9539 case llvm::Triple::sparc: 9540 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types)); 9541 case llvm::Triple::sparcv9: 9542 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types)); 9543 case llvm::Triple::xcore: 9544 return SetCGInfo(new XCoreTargetCodeGenInfo(Types)); 9545 case llvm::Triple::arc: 9546 return SetCGInfo(new ARCTargetCodeGenInfo(Types)); 9547 case llvm::Triple::spir: 9548 case llvm::Triple::spir64: 9549 return SetCGInfo(new SPIRTargetCodeGenInfo(Types)); 9550 } 9551 } 9552 9553 /// Create an OpenCL kernel for an enqueued block. 9554 /// 9555 /// The kernel has the same function type as the block invoke function. Its 9556 /// name is the name of the block invoke function postfixed with "_kernel". 9557 /// It simply calls the block invoke function then returns. 9558 llvm::Function * 9559 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF, 9560 llvm::Function *Invoke, 9561 llvm::Value *BlockLiteral) const { 9562 auto *InvokeFT = Invoke->getFunctionType(); 9563 llvm::SmallVector<llvm::Type *, 2> ArgTys; 9564 for (auto &P : InvokeFT->params()) 9565 ArgTys.push_back(P); 9566 auto &C = CGF.getLLVMContext(); 9567 std::string Name = Invoke->getName().str() + "_kernel"; 9568 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 9569 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 9570 &CGF.CGM.getModule()); 9571 auto IP = CGF.Builder.saveIP(); 9572 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 9573 auto &Builder = CGF.Builder; 9574 Builder.SetInsertPoint(BB); 9575 llvm::SmallVector<llvm::Value *, 2> Args; 9576 for (auto &A : F->args()) 9577 Args.push_back(&A); 9578 Builder.CreateCall(Invoke, Args); 9579 Builder.CreateRetVoid(); 9580 Builder.restoreIP(IP); 9581 return F; 9582 } 9583 9584 /// Create an OpenCL kernel for an enqueued block. 9585 /// 9586 /// The type of the first argument (the block literal) is the struct type 9587 /// of the block literal instead of a pointer type. The first argument 9588 /// (block literal) is passed directly by value to the kernel. The kernel 9589 /// allocates the same type of struct on stack and stores the block literal 9590 /// to it and passes its pointer to the block invoke function. The kernel 9591 /// has "enqueued-block" function attribute and kernel argument metadata. 9592 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel( 9593 CodeGenFunction &CGF, llvm::Function *Invoke, 9594 llvm::Value *BlockLiteral) const { 9595 auto &Builder = CGF.Builder; 9596 auto &C = CGF.getLLVMContext(); 9597 9598 auto *BlockTy = BlockLiteral->getType()->getPointerElementType(); 9599 auto *InvokeFT = Invoke->getFunctionType(); 9600 llvm::SmallVector<llvm::Type *, 2> ArgTys; 9601 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals; 9602 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals; 9603 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames; 9604 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames; 9605 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals; 9606 llvm::SmallVector<llvm::Metadata *, 8> ArgNames; 9607 9608 ArgTys.push_back(BlockTy); 9609 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 9610 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0))); 9611 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal")); 9612 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 9613 AccessQuals.push_back(llvm::MDString::get(C, "none")); 9614 ArgNames.push_back(llvm::MDString::get(C, "block_literal")); 9615 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) { 9616 ArgTys.push_back(InvokeFT->getParamType(I)); 9617 ArgTypeNames.push_back(llvm::MDString::get(C, "void*")); 9618 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3))); 9619 AccessQuals.push_back(llvm::MDString::get(C, "none")); 9620 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*")); 9621 ArgTypeQuals.push_back(llvm::MDString::get(C, "")); 9622 ArgNames.push_back( 9623 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str())); 9624 } 9625 std::string Name = Invoke->getName().str() + "_kernel"; 9626 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false); 9627 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name, 9628 &CGF.CGM.getModule()); 9629 F->addFnAttr("enqueued-block"); 9630 auto IP = CGF.Builder.saveIP(); 9631 auto *BB = llvm::BasicBlock::Create(C, "entry", F); 9632 Builder.SetInsertPoint(BB); 9633 unsigned BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(BlockTy); 9634 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr); 9635 BlockPtr->setAlignment(BlockAlign); 9636 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign); 9637 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0)); 9638 llvm::SmallVector<llvm::Value *, 2> Args; 9639 Args.push_back(Cast); 9640 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I) 9641 Args.push_back(I); 9642 Builder.CreateCall(Invoke, Args); 9643 Builder.CreateRetVoid(); 9644 Builder.restoreIP(IP); 9645 9646 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals)); 9647 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals)); 9648 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames)); 9649 F->setMetadata("kernel_arg_base_type", 9650 llvm::MDNode::get(C, ArgBaseTypeNames)); 9651 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals)); 9652 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata) 9653 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames)); 9654 9655 return F; 9656 } 9657