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