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