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