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