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