1 //===--- Compiler.cpp - Code generator for expressions ---*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "Compiler.h" 10 #include "ByteCodeEmitter.h" 11 #include "Context.h" 12 #include "Floating.h" 13 #include "Function.h" 14 #include "InterpShared.h" 15 #include "PrimType.h" 16 #include "Program.h" 17 #include "clang/AST/Attr.h" 18 19 using namespace clang; 20 using namespace clang::interp; 21 22 using APSInt = llvm::APSInt; 23 24 namespace clang { 25 namespace interp { 26 27 /// Scope used to handle temporaries in toplevel variable declarations. 28 template <class Emitter> class DeclScope final : public LocalScope<Emitter> { 29 public: 30 DeclScope(Compiler<Emitter> *Ctx, const ValueDecl *VD) 31 : LocalScope<Emitter>(Ctx, VD), Scope(Ctx->P, VD), 32 OldInitializingDecl(Ctx->InitializingDecl) { 33 Ctx->InitializingDecl = VD; 34 Ctx->InitStack.push_back(InitLink::Decl(VD)); 35 } 36 37 void addExtended(const Scope::Local &Local) override { 38 return this->addLocal(Local); 39 } 40 41 ~DeclScope() { 42 this->Ctx->InitializingDecl = OldInitializingDecl; 43 this->Ctx->InitStack.pop_back(); 44 } 45 46 private: 47 Program::DeclScope Scope; 48 const ValueDecl *OldInitializingDecl; 49 }; 50 51 /// Scope used to handle initialization methods. 52 template <class Emitter> class OptionScope final { 53 public: 54 /// Root constructor, compiling or discarding primitives. 55 OptionScope(Compiler<Emitter> *Ctx, bool NewDiscardResult, 56 bool NewInitializing) 57 : Ctx(Ctx), OldDiscardResult(Ctx->DiscardResult), 58 OldInitializing(Ctx->Initializing) { 59 Ctx->DiscardResult = NewDiscardResult; 60 Ctx->Initializing = NewInitializing; 61 } 62 63 ~OptionScope() { 64 Ctx->DiscardResult = OldDiscardResult; 65 Ctx->Initializing = OldInitializing; 66 } 67 68 private: 69 /// Parent context. 70 Compiler<Emitter> *Ctx; 71 /// Old discard flag to restore. 72 bool OldDiscardResult; 73 bool OldInitializing; 74 }; 75 76 template <class Emitter> 77 bool InitLink::emit(Compiler<Emitter> *Ctx, const Expr *E) const { 78 switch (Kind) { 79 case K_This: 80 return Ctx->emitThis(E); 81 case K_Field: 82 // We're assuming there's a base pointer on the stack already. 83 return Ctx->emitGetPtrFieldPop(Offset, E); 84 case K_Temp: 85 return Ctx->emitGetPtrLocal(Offset, E); 86 case K_Decl: 87 return Ctx->visitDeclRef(D, E); 88 case K_Elem: 89 if (!Ctx->emitConstUint32(Offset, E)) 90 return false; 91 return Ctx->emitArrayElemPtrPopUint32(E); 92 default: 93 llvm_unreachable("Unhandled InitLink kind"); 94 } 95 return true; 96 } 97 98 /// Scope managing label targets. 99 template <class Emitter> class LabelScope { 100 public: 101 virtual ~LabelScope() {} 102 103 protected: 104 LabelScope(Compiler<Emitter> *Ctx) : Ctx(Ctx) {} 105 /// Compiler instance. 106 Compiler<Emitter> *Ctx; 107 }; 108 109 /// Sets the context for break/continue statements. 110 template <class Emitter> class LoopScope final : public LabelScope<Emitter> { 111 public: 112 using LabelTy = typename Compiler<Emitter>::LabelTy; 113 using OptLabelTy = typename Compiler<Emitter>::OptLabelTy; 114 115 LoopScope(Compiler<Emitter> *Ctx, LabelTy BreakLabel, LabelTy ContinueLabel) 116 : LabelScope<Emitter>(Ctx), OldBreakLabel(Ctx->BreakLabel), 117 OldContinueLabel(Ctx->ContinueLabel) { 118 this->Ctx->BreakLabel = BreakLabel; 119 this->Ctx->ContinueLabel = ContinueLabel; 120 } 121 122 ~LoopScope() { 123 this->Ctx->BreakLabel = OldBreakLabel; 124 this->Ctx->ContinueLabel = OldContinueLabel; 125 } 126 127 private: 128 OptLabelTy OldBreakLabel; 129 OptLabelTy OldContinueLabel; 130 }; 131 132 // Sets the context for a switch scope, mapping labels. 133 template <class Emitter> class SwitchScope final : public LabelScope<Emitter> { 134 public: 135 using LabelTy = typename Compiler<Emitter>::LabelTy; 136 using OptLabelTy = typename Compiler<Emitter>::OptLabelTy; 137 using CaseMap = typename Compiler<Emitter>::CaseMap; 138 139 SwitchScope(Compiler<Emitter> *Ctx, CaseMap &&CaseLabels, LabelTy BreakLabel, 140 OptLabelTy DefaultLabel) 141 : LabelScope<Emitter>(Ctx), OldBreakLabel(Ctx->BreakLabel), 142 OldDefaultLabel(this->Ctx->DefaultLabel), 143 OldCaseLabels(std::move(this->Ctx->CaseLabels)) { 144 this->Ctx->BreakLabel = BreakLabel; 145 this->Ctx->DefaultLabel = DefaultLabel; 146 this->Ctx->CaseLabels = std::move(CaseLabels); 147 } 148 149 ~SwitchScope() { 150 this->Ctx->BreakLabel = OldBreakLabel; 151 this->Ctx->DefaultLabel = OldDefaultLabel; 152 this->Ctx->CaseLabels = std::move(OldCaseLabels); 153 } 154 155 private: 156 OptLabelTy OldBreakLabel; 157 OptLabelTy OldDefaultLabel; 158 CaseMap OldCaseLabels; 159 }; 160 161 template <class Emitter> class StmtExprScope final { 162 public: 163 StmtExprScope(Compiler<Emitter> *Ctx) : Ctx(Ctx), OldFlag(Ctx->InStmtExpr) { 164 Ctx->InStmtExpr = true; 165 } 166 167 ~StmtExprScope() { Ctx->InStmtExpr = OldFlag; } 168 169 private: 170 Compiler<Emitter> *Ctx; 171 bool OldFlag; 172 }; 173 174 } // namespace interp 175 } // namespace clang 176 177 template <class Emitter> 178 bool Compiler<Emitter>::VisitCastExpr(const CastExpr *CE) { 179 const Expr *SubExpr = CE->getSubExpr(); 180 switch (CE->getCastKind()) { 181 182 case CK_LValueToRValue: { 183 if (DiscardResult) 184 return this->discard(SubExpr); 185 186 std::optional<PrimType> SubExprT = classify(SubExpr->getType()); 187 // Prepare storage for the result. 188 if (!Initializing && !SubExprT) { 189 std::optional<unsigned> LocalIndex = allocateLocal(SubExpr); 190 if (!LocalIndex) 191 return false; 192 if (!this->emitGetPtrLocal(*LocalIndex, CE)) 193 return false; 194 } 195 196 if (!this->visit(SubExpr)) 197 return false; 198 199 if (SubExprT) 200 return this->emitLoadPop(*SubExprT, CE); 201 202 // If the subexpr type is not primitive, we need to perform a copy here. 203 // This happens for example in C when dereferencing a pointer of struct 204 // type. 205 return this->emitMemcpy(CE); 206 } 207 208 case CK_DerivedToBaseMemberPointer: { 209 assert(classifyPrim(CE->getType()) == PT_MemberPtr); 210 assert(classifyPrim(SubExpr->getType()) == PT_MemberPtr); 211 const auto *FromMP = SubExpr->getType()->getAs<MemberPointerType>(); 212 const auto *ToMP = CE->getType()->getAs<MemberPointerType>(); 213 214 unsigned DerivedOffset = collectBaseOffset(QualType(ToMP->getClass(), 0), 215 QualType(FromMP->getClass(), 0)); 216 217 if (!this->delegate(SubExpr)) 218 return false; 219 220 return this->emitGetMemberPtrBasePop(DerivedOffset, CE); 221 } 222 223 case CK_BaseToDerivedMemberPointer: { 224 assert(classifyPrim(CE) == PT_MemberPtr); 225 assert(classifyPrim(SubExpr) == PT_MemberPtr); 226 const auto *FromMP = SubExpr->getType()->getAs<MemberPointerType>(); 227 const auto *ToMP = CE->getType()->getAs<MemberPointerType>(); 228 229 unsigned DerivedOffset = collectBaseOffset(QualType(FromMP->getClass(), 0), 230 QualType(ToMP->getClass(), 0)); 231 232 if (!this->delegate(SubExpr)) 233 return false; 234 return this->emitGetMemberPtrBasePop(-DerivedOffset, CE); 235 } 236 237 case CK_UncheckedDerivedToBase: 238 case CK_DerivedToBase: { 239 if (!this->delegate(SubExpr)) 240 return false; 241 242 const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * { 243 if (const auto *PT = dyn_cast<PointerType>(Ty)) 244 return PT->getPointeeType()->getAsCXXRecordDecl(); 245 return Ty->getAsCXXRecordDecl(); 246 }; 247 248 // FIXME: We can express a series of non-virtual casts as a single 249 // GetPtrBasePop op. 250 QualType CurType = SubExpr->getType(); 251 for (const CXXBaseSpecifier *B : CE->path()) { 252 if (B->isVirtual()) { 253 if (!this->emitGetPtrVirtBasePop(extractRecordDecl(B->getType()), CE)) 254 return false; 255 CurType = B->getType(); 256 } else { 257 unsigned DerivedOffset = collectBaseOffset(B->getType(), CurType); 258 if (!this->emitGetPtrBasePop(DerivedOffset, CE)) 259 return false; 260 CurType = B->getType(); 261 } 262 } 263 264 return true; 265 } 266 267 case CK_BaseToDerived: { 268 if (!this->delegate(SubExpr)) 269 return false; 270 271 unsigned DerivedOffset = 272 collectBaseOffset(SubExpr->getType(), CE->getType()); 273 274 return this->emitGetPtrDerivedPop(DerivedOffset, CE); 275 } 276 277 case CK_FloatingCast: { 278 // HLSL uses CK_FloatingCast to cast between vectors. 279 if (!SubExpr->getType()->isFloatingType() || 280 !CE->getType()->isFloatingType()) 281 return false; 282 if (DiscardResult) 283 return this->discard(SubExpr); 284 if (!this->visit(SubExpr)) 285 return false; 286 const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType()); 287 return this->emitCastFP(TargetSemantics, getRoundingMode(CE), CE); 288 } 289 290 case CK_IntegralToFloating: { 291 if (DiscardResult) 292 return this->discard(SubExpr); 293 std::optional<PrimType> FromT = classify(SubExpr->getType()); 294 if (!FromT) 295 return false; 296 297 if (!this->visit(SubExpr)) 298 return false; 299 300 const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType()); 301 llvm::RoundingMode RM = getRoundingMode(CE); 302 return this->emitCastIntegralFloating(*FromT, TargetSemantics, RM, CE); 303 } 304 305 case CK_FloatingToBoolean: 306 case CK_FloatingToIntegral: { 307 if (DiscardResult) 308 return this->discard(SubExpr); 309 310 std::optional<PrimType> ToT = classify(CE->getType()); 311 312 if (!ToT) 313 return false; 314 315 if (!this->visit(SubExpr)) 316 return false; 317 318 if (ToT == PT_IntAP) 319 return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(CE->getType()), 320 CE); 321 if (ToT == PT_IntAPS) 322 return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(CE->getType()), 323 CE); 324 325 return this->emitCastFloatingIntegral(*ToT, CE); 326 } 327 328 case CK_NullToPointer: 329 case CK_NullToMemberPointer: { 330 if (!this->discard(SubExpr)) 331 return false; 332 if (DiscardResult) 333 return true; 334 335 const Descriptor *Desc = nullptr; 336 const QualType PointeeType = CE->getType()->getPointeeType(); 337 if (!PointeeType.isNull()) { 338 if (std::optional<PrimType> T = classify(PointeeType)) 339 Desc = P.createDescriptor(SubExpr, *T); 340 else 341 Desc = P.createDescriptor(SubExpr, PointeeType.getTypePtr(), 342 std::nullopt, true, false, 343 /*IsMutable=*/false, nullptr); 344 } 345 return this->emitNull(classifyPrim(CE->getType()), Desc, CE); 346 } 347 348 case CK_PointerToIntegral: { 349 if (DiscardResult) 350 return this->discard(SubExpr); 351 352 if (!this->visit(SubExpr)) 353 return false; 354 355 // If SubExpr doesn't result in a pointer, make it one. 356 if (PrimType FromT = classifyPrim(SubExpr->getType()); FromT != PT_Ptr) { 357 assert(isPtrType(FromT)); 358 if (!this->emitDecayPtr(FromT, PT_Ptr, CE)) 359 return false; 360 } 361 362 PrimType T = classifyPrim(CE->getType()); 363 if (T == PT_IntAP) 364 return this->emitCastPointerIntegralAP(Ctx.getBitWidth(CE->getType()), 365 CE); 366 if (T == PT_IntAPS) 367 return this->emitCastPointerIntegralAPS(Ctx.getBitWidth(CE->getType()), 368 CE); 369 return this->emitCastPointerIntegral(T, CE); 370 } 371 372 case CK_ArrayToPointerDecay: { 373 if (!this->visit(SubExpr)) 374 return false; 375 if (!this->emitArrayDecay(CE)) 376 return false; 377 if (DiscardResult) 378 return this->emitPopPtr(CE); 379 return true; 380 } 381 382 case CK_IntegralToPointer: { 383 QualType IntType = SubExpr->getType(); 384 assert(IntType->isIntegralOrEnumerationType()); 385 if (!this->visit(SubExpr)) 386 return false; 387 // FIXME: I think the discard is wrong since the int->ptr cast might cause a 388 // diagnostic. 389 PrimType T = classifyPrim(IntType); 390 if (DiscardResult) 391 return this->emitPop(T, CE); 392 393 QualType PtrType = CE->getType(); 394 const Descriptor *Desc; 395 if (std::optional<PrimType> T = classify(PtrType->getPointeeType())) 396 Desc = P.createDescriptor(SubExpr, *T); 397 else if (PtrType->getPointeeType()->isVoidType()) 398 Desc = nullptr; 399 else 400 Desc = P.createDescriptor(CE, PtrType->getPointeeType().getTypePtr(), 401 Descriptor::InlineDescMD, true, false, 402 /*IsMutable=*/false, nullptr); 403 404 if (!this->emitGetIntPtr(T, Desc, CE)) 405 return false; 406 407 PrimType DestPtrT = classifyPrim(PtrType); 408 if (DestPtrT == PT_Ptr) 409 return true; 410 411 // In case we're converting the integer to a non-Pointer. 412 return this->emitDecayPtr(PT_Ptr, DestPtrT, CE); 413 } 414 415 case CK_AtomicToNonAtomic: 416 case CK_ConstructorConversion: 417 case CK_FunctionToPointerDecay: 418 case CK_NonAtomicToAtomic: 419 case CK_NoOp: 420 case CK_UserDefinedConversion: 421 case CK_AddressSpaceConversion: 422 return this->delegate(SubExpr); 423 424 case CK_BitCast: { 425 // Reject bitcasts to atomic types. 426 if (CE->getType()->isAtomicType()) { 427 if (!this->discard(SubExpr)) 428 return false; 429 return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, CE); 430 } 431 432 if (DiscardResult) 433 return this->discard(SubExpr); 434 435 QualType SubExprTy = SubExpr->getType(); 436 std::optional<PrimType> FromT = classify(SubExprTy); 437 std::optional<PrimType> ToT = classify(CE->getType()); 438 if (!FromT || !ToT) 439 return false; 440 441 assert(isPtrType(*FromT)); 442 assert(isPtrType(*ToT)); 443 if (FromT == ToT) { 444 if (CE->getType()->isVoidPointerType()) 445 return this->delegate(SubExpr); 446 447 if (!this->visit(SubExpr)) 448 return false; 449 if (FromT == PT_Ptr) 450 return this->emitPtrPtrCast(SubExprTy->isVoidPointerType(), CE); 451 return true; 452 } 453 454 if (!this->visit(SubExpr)) 455 return false; 456 return this->emitDecayPtr(*FromT, *ToT, CE); 457 } 458 459 case CK_IntegralToBoolean: 460 case CK_BooleanToSignedIntegral: 461 case CK_IntegralCast: { 462 if (DiscardResult) 463 return this->discard(SubExpr); 464 std::optional<PrimType> FromT = classify(SubExpr->getType()); 465 std::optional<PrimType> ToT = classify(CE->getType()); 466 467 if (!FromT || !ToT) 468 return false; 469 470 if (!this->visit(SubExpr)) 471 return false; 472 473 // Possibly diagnose casts to enum types if the target type does not 474 // have a fixed size. 475 if (Ctx.getLangOpts().CPlusPlus && CE->getType()->isEnumeralType()) { 476 if (const auto *ET = CE->getType().getCanonicalType()->getAs<EnumType>(); 477 ET && !ET->getDecl()->isFixed()) { 478 if (!this->emitCheckEnumValue(*FromT, ET->getDecl(), CE)) 479 return false; 480 } 481 } 482 483 auto maybeNegate = [&]() -> bool { 484 if (CE->getCastKind() == CK_BooleanToSignedIntegral) 485 return this->emitNeg(*ToT, CE); 486 return true; 487 }; 488 489 if (ToT == PT_IntAP) 490 return this->emitCastAP(*FromT, Ctx.getBitWidth(CE->getType()), CE) && 491 maybeNegate(); 492 if (ToT == PT_IntAPS) 493 return this->emitCastAPS(*FromT, Ctx.getBitWidth(CE->getType()), CE) && 494 maybeNegate(); 495 496 if (FromT == ToT) 497 return true; 498 if (!this->emitCast(*FromT, *ToT, CE)) 499 return false; 500 501 return maybeNegate(); 502 } 503 504 case CK_PointerToBoolean: 505 case CK_MemberPointerToBoolean: { 506 PrimType PtrT = classifyPrim(SubExpr->getType()); 507 508 // Just emit p != nullptr for this. 509 if (!this->visit(SubExpr)) 510 return false; 511 512 if (!this->emitNull(PtrT, nullptr, CE)) 513 return false; 514 515 return this->emitNE(PtrT, CE); 516 } 517 518 case CK_IntegralComplexToBoolean: 519 case CK_FloatingComplexToBoolean: { 520 if (DiscardResult) 521 return this->discard(SubExpr); 522 if (!this->visit(SubExpr)) 523 return false; 524 return this->emitComplexBoolCast(SubExpr); 525 } 526 527 case CK_IntegralComplexToReal: 528 case CK_FloatingComplexToReal: 529 return this->emitComplexReal(SubExpr); 530 531 case CK_IntegralRealToComplex: 532 case CK_FloatingRealToComplex: { 533 // We're creating a complex value here, so we need to 534 // allocate storage for it. 535 if (!Initializing) { 536 unsigned LocalIndex = allocateTemporary(CE); 537 if (!this->emitGetPtrLocal(LocalIndex, CE)) 538 return false; 539 } 540 541 // Init the complex value to {SubExpr, 0}. 542 if (!this->visitArrayElemInit(0, SubExpr)) 543 return false; 544 // Zero-init the second element. 545 PrimType T = classifyPrim(SubExpr->getType()); 546 if (!this->visitZeroInitializer(T, SubExpr->getType(), SubExpr)) 547 return false; 548 return this->emitInitElem(T, 1, SubExpr); 549 } 550 551 case CK_IntegralComplexCast: 552 case CK_FloatingComplexCast: 553 case CK_IntegralComplexToFloatingComplex: 554 case CK_FloatingComplexToIntegralComplex: { 555 assert(CE->getType()->isAnyComplexType()); 556 assert(SubExpr->getType()->isAnyComplexType()); 557 if (DiscardResult) 558 return this->discard(SubExpr); 559 560 if (!Initializing) { 561 std::optional<unsigned> LocalIndex = allocateLocal(CE); 562 if (!LocalIndex) 563 return false; 564 if (!this->emitGetPtrLocal(*LocalIndex, CE)) 565 return false; 566 } 567 568 // Location for the SubExpr. 569 // Since SubExpr is of complex type, visiting it results in a pointer 570 // anyway, so we just create a temporary pointer variable. 571 unsigned SubExprOffset = allocateLocalPrimitive( 572 SubExpr, PT_Ptr, /*IsConst=*/true, /*IsExtended=*/false); 573 if (!this->visit(SubExpr)) 574 return false; 575 if (!this->emitSetLocal(PT_Ptr, SubExprOffset, CE)) 576 return false; 577 578 PrimType SourceElemT = classifyComplexElementType(SubExpr->getType()); 579 QualType DestElemType = 580 CE->getType()->getAs<ComplexType>()->getElementType(); 581 PrimType DestElemT = classifyPrim(DestElemType); 582 // Cast both elements individually. 583 for (unsigned I = 0; I != 2; ++I) { 584 if (!this->emitGetLocal(PT_Ptr, SubExprOffset, CE)) 585 return false; 586 if (!this->emitArrayElemPop(SourceElemT, I, CE)) 587 return false; 588 589 // Do the cast. 590 if (!this->emitPrimCast(SourceElemT, DestElemT, DestElemType, CE)) 591 return false; 592 593 // Save the value. 594 if (!this->emitInitElem(DestElemT, I, CE)) 595 return false; 596 } 597 return true; 598 } 599 600 case CK_VectorSplat: { 601 assert(!classify(CE->getType())); 602 assert(classify(SubExpr->getType())); 603 assert(CE->getType()->isVectorType()); 604 605 if (DiscardResult) 606 return this->discard(SubExpr); 607 608 if (!Initializing) { 609 std::optional<unsigned> LocalIndex = allocateLocal(CE); 610 if (!LocalIndex) 611 return false; 612 if (!this->emitGetPtrLocal(*LocalIndex, CE)) 613 return false; 614 } 615 616 const auto *VT = CE->getType()->getAs<VectorType>(); 617 PrimType ElemT = classifyPrim(SubExpr->getType()); 618 unsigned ElemOffset = allocateLocalPrimitive( 619 SubExpr, ElemT, /*IsConst=*/true, /*IsExtended=*/false); 620 621 // Prepare a local variable for the scalar value. 622 if (!this->visit(SubExpr)) 623 return false; 624 if (classifyPrim(SubExpr) == PT_Ptr && !this->emitLoadPop(ElemT, CE)) 625 return false; 626 627 if (!this->emitSetLocal(ElemT, ElemOffset, CE)) 628 return false; 629 630 for (unsigned I = 0; I != VT->getNumElements(); ++I) { 631 if (!this->emitGetLocal(ElemT, ElemOffset, CE)) 632 return false; 633 if (!this->emitInitElem(ElemT, I, CE)) 634 return false; 635 } 636 637 return true; 638 } 639 640 case CK_ToVoid: 641 return discard(SubExpr); 642 643 default: 644 return this->emitInvalid(CE); 645 } 646 llvm_unreachable("Unhandled clang::CastKind enum"); 647 } 648 649 template <class Emitter> 650 bool Compiler<Emitter>::VisitIntegerLiteral(const IntegerLiteral *LE) { 651 if (DiscardResult) 652 return true; 653 654 return this->emitConst(LE->getValue(), LE); 655 } 656 657 template <class Emitter> 658 bool Compiler<Emitter>::VisitFloatingLiteral(const FloatingLiteral *E) { 659 if (DiscardResult) 660 return true; 661 662 return this->emitConstFloat(E->getValue(), E); 663 } 664 665 template <class Emitter> 666 bool Compiler<Emitter>::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 667 assert(E->getType()->isAnyComplexType()); 668 if (DiscardResult) 669 return true; 670 671 if (!Initializing) { 672 unsigned LocalIndex = allocateTemporary(E); 673 if (!this->emitGetPtrLocal(LocalIndex, E)) 674 return false; 675 } 676 677 const Expr *SubExpr = E->getSubExpr(); 678 PrimType SubExprT = classifyPrim(SubExpr->getType()); 679 680 if (!this->visitZeroInitializer(SubExprT, SubExpr->getType(), SubExpr)) 681 return false; 682 if (!this->emitInitElem(SubExprT, 0, SubExpr)) 683 return false; 684 return this->visitArrayElemInit(1, SubExpr); 685 } 686 687 template <class Emitter> 688 bool Compiler<Emitter>::VisitParenExpr(const ParenExpr *E) { 689 return this->delegate(E->getSubExpr()); 690 } 691 692 template <class Emitter> 693 bool Compiler<Emitter>::VisitBinaryOperator(const BinaryOperator *BO) { 694 // Need short-circuiting for these. 695 if (BO->isLogicalOp()) 696 return this->VisitLogicalBinOp(BO); 697 698 const Expr *LHS = BO->getLHS(); 699 const Expr *RHS = BO->getRHS(); 700 701 // Handle comma operators. Just discard the LHS 702 // and delegate to RHS. 703 if (BO->isCommaOp()) { 704 if (!this->discard(LHS)) 705 return false; 706 if (RHS->getType()->isVoidType()) 707 return this->discard(RHS); 708 709 return this->delegate(RHS); 710 } 711 712 if (BO->getType()->isAnyComplexType()) 713 return this->VisitComplexBinOp(BO); 714 if ((LHS->getType()->isAnyComplexType() || 715 RHS->getType()->isAnyComplexType()) && 716 BO->isComparisonOp()) 717 return this->emitComplexComparison(LHS, RHS, BO); 718 719 if (BO->isPtrMemOp()) { 720 if (!this->visit(LHS)) 721 return false; 722 723 if (!this->visit(RHS)) 724 return false; 725 726 if (!this->emitToMemberPtr(BO)) 727 return false; 728 729 if (classifyPrim(BO) == PT_MemberPtr) 730 return true; 731 732 if (!this->emitCastMemberPtrPtr(BO)) 733 return false; 734 return DiscardResult ? this->emitPopPtr(BO) : true; 735 } 736 737 // Typecheck the args. 738 std::optional<PrimType> LT = classify(LHS); 739 std::optional<PrimType> RT = classify(RHS); 740 std::optional<PrimType> T = classify(BO->getType()); 741 742 // Special case for C++'s three-way/spaceship operator <=>, which 743 // returns a std::{strong,weak,partial}_ordering (which is a class, so doesn't 744 // have a PrimType). 745 if (!T && BO->getOpcode() == BO_Cmp) { 746 if (DiscardResult) 747 return true; 748 const ComparisonCategoryInfo *CmpInfo = 749 Ctx.getASTContext().CompCategories.lookupInfoForType(BO->getType()); 750 assert(CmpInfo); 751 752 // We need a temporary variable holding our return value. 753 if (!Initializing) { 754 std::optional<unsigned> ResultIndex = this->allocateLocal(BO); 755 if (!this->emitGetPtrLocal(*ResultIndex, BO)) 756 return false; 757 } 758 759 if (!visit(LHS) || !visit(RHS)) 760 return false; 761 762 return this->emitCMP3(*LT, CmpInfo, BO); 763 } 764 765 if (!LT || !RT || !T) 766 return false; 767 768 // Pointer arithmetic special case. 769 if (BO->getOpcode() == BO_Add || BO->getOpcode() == BO_Sub) { 770 if (isPtrType(*T) || (isPtrType(*LT) && isPtrType(*RT))) 771 return this->VisitPointerArithBinOp(BO); 772 } 773 774 // Assignmentes require us to evalute the RHS first. 775 if (BO->getOpcode() == BO_Assign) { 776 if (!visit(RHS) || !visit(LHS)) 777 return false; 778 if (!this->emitFlip(*LT, *RT, BO)) 779 return false; 780 } else { 781 if (!visit(LHS) || !visit(RHS)) 782 return false; 783 } 784 785 // For languages such as C, cast the result of one 786 // of our comparision opcodes to T (which is usually int). 787 auto MaybeCastToBool = [this, T, BO](bool Result) { 788 if (!Result) 789 return false; 790 if (DiscardResult) 791 return this->emitPop(*T, BO); 792 if (T != PT_Bool) 793 return this->emitCast(PT_Bool, *T, BO); 794 return true; 795 }; 796 797 auto Discard = [this, T, BO](bool Result) { 798 if (!Result) 799 return false; 800 return DiscardResult ? this->emitPop(*T, BO) : true; 801 }; 802 803 switch (BO->getOpcode()) { 804 case BO_EQ: 805 return MaybeCastToBool(this->emitEQ(*LT, BO)); 806 case BO_NE: 807 return MaybeCastToBool(this->emitNE(*LT, BO)); 808 case BO_LT: 809 return MaybeCastToBool(this->emitLT(*LT, BO)); 810 case BO_LE: 811 return MaybeCastToBool(this->emitLE(*LT, BO)); 812 case BO_GT: 813 return MaybeCastToBool(this->emitGT(*LT, BO)); 814 case BO_GE: 815 return MaybeCastToBool(this->emitGE(*LT, BO)); 816 case BO_Sub: 817 if (BO->getType()->isFloatingType()) 818 return Discard(this->emitSubf(getRoundingMode(BO), BO)); 819 return Discard(this->emitSub(*T, BO)); 820 case BO_Add: 821 if (BO->getType()->isFloatingType()) 822 return Discard(this->emitAddf(getRoundingMode(BO), BO)); 823 return Discard(this->emitAdd(*T, BO)); 824 case BO_Mul: 825 if (BO->getType()->isFloatingType()) 826 return Discard(this->emitMulf(getRoundingMode(BO), BO)); 827 return Discard(this->emitMul(*T, BO)); 828 case BO_Rem: 829 return Discard(this->emitRem(*T, BO)); 830 case BO_Div: 831 if (BO->getType()->isFloatingType()) 832 return Discard(this->emitDivf(getRoundingMode(BO), BO)); 833 return Discard(this->emitDiv(*T, BO)); 834 case BO_Assign: 835 if (DiscardResult) 836 return LHS->refersToBitField() ? this->emitStoreBitFieldPop(*T, BO) 837 : this->emitStorePop(*T, BO); 838 if (LHS->refersToBitField()) { 839 if (!this->emitStoreBitField(*T, BO)) 840 return false; 841 } else { 842 if (!this->emitStore(*T, BO)) 843 return false; 844 } 845 // Assignments aren't necessarily lvalues in C. 846 // Load from them in that case. 847 if (!BO->isLValue()) 848 return this->emitLoadPop(*T, BO); 849 return true; 850 case BO_And: 851 return Discard(this->emitBitAnd(*T, BO)); 852 case BO_Or: 853 return Discard(this->emitBitOr(*T, BO)); 854 case BO_Shl: 855 return Discard(this->emitShl(*LT, *RT, BO)); 856 case BO_Shr: 857 return Discard(this->emitShr(*LT, *RT, BO)); 858 case BO_Xor: 859 return Discard(this->emitBitXor(*T, BO)); 860 case BO_LOr: 861 case BO_LAnd: 862 llvm_unreachable("Already handled earlier"); 863 default: 864 return false; 865 } 866 867 llvm_unreachable("Unhandled binary op"); 868 } 869 870 /// Perform addition/subtraction of a pointer and an integer or 871 /// subtraction of two pointers. 872 template <class Emitter> 873 bool Compiler<Emitter>::VisitPointerArithBinOp(const BinaryOperator *E) { 874 BinaryOperatorKind Op = E->getOpcode(); 875 const Expr *LHS = E->getLHS(); 876 const Expr *RHS = E->getRHS(); 877 878 if ((Op != BO_Add && Op != BO_Sub) || 879 (!LHS->getType()->isPointerType() && !RHS->getType()->isPointerType())) 880 return false; 881 882 std::optional<PrimType> LT = classify(LHS); 883 std::optional<PrimType> RT = classify(RHS); 884 885 if (!LT || !RT) 886 return false; 887 888 // Visit the given pointer expression and optionally convert to a PT_Ptr. 889 auto visitAsPointer = [&](const Expr *E, PrimType T) -> bool { 890 if (!this->visit(E)) 891 return false; 892 if (T != PT_Ptr) 893 return this->emitDecayPtr(T, PT_Ptr, E); 894 return true; 895 }; 896 897 if (LHS->getType()->isPointerType() && RHS->getType()->isPointerType()) { 898 if (Op != BO_Sub) 899 return false; 900 901 assert(E->getType()->isIntegerType()); 902 if (!visitAsPointer(RHS, *RT) || !visitAsPointer(LHS, *LT)) 903 return false; 904 905 return this->emitSubPtr(classifyPrim(E->getType()), E); 906 } 907 908 PrimType OffsetType; 909 if (LHS->getType()->isIntegerType()) { 910 if (!visitAsPointer(RHS, *RT)) 911 return false; 912 if (!this->visit(LHS)) 913 return false; 914 OffsetType = *LT; 915 } else if (RHS->getType()->isIntegerType()) { 916 if (!visitAsPointer(LHS, *LT)) 917 return false; 918 if (!this->visit(RHS)) 919 return false; 920 OffsetType = *RT; 921 } else { 922 return false; 923 } 924 925 // Do the operation and optionally transform to 926 // result pointer type. 927 if (Op == BO_Add) { 928 if (!this->emitAddOffset(OffsetType, E)) 929 return false; 930 931 if (classifyPrim(E) != PT_Ptr) 932 return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E); 933 return true; 934 } else if (Op == BO_Sub) { 935 if (!this->emitSubOffset(OffsetType, E)) 936 return false; 937 938 if (classifyPrim(E) != PT_Ptr) 939 return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E); 940 return true; 941 } 942 943 return false; 944 } 945 946 template <class Emitter> 947 bool Compiler<Emitter>::VisitLogicalBinOp(const BinaryOperator *E) { 948 assert(E->isLogicalOp()); 949 BinaryOperatorKind Op = E->getOpcode(); 950 const Expr *LHS = E->getLHS(); 951 const Expr *RHS = E->getRHS(); 952 std::optional<PrimType> T = classify(E->getType()); 953 954 if (Op == BO_LOr) { 955 // Logical OR. Visit LHS and only evaluate RHS if LHS was FALSE. 956 LabelTy LabelTrue = this->getLabel(); 957 LabelTy LabelEnd = this->getLabel(); 958 959 if (!this->visitBool(LHS)) 960 return false; 961 if (!this->jumpTrue(LabelTrue)) 962 return false; 963 964 if (!this->visitBool(RHS)) 965 return false; 966 if (!this->jump(LabelEnd)) 967 return false; 968 969 this->emitLabel(LabelTrue); 970 this->emitConstBool(true, E); 971 this->fallthrough(LabelEnd); 972 this->emitLabel(LabelEnd); 973 974 } else { 975 assert(Op == BO_LAnd); 976 // Logical AND. 977 // Visit LHS. Only visit RHS if LHS was TRUE. 978 LabelTy LabelFalse = this->getLabel(); 979 LabelTy LabelEnd = this->getLabel(); 980 981 if (!this->visitBool(LHS)) 982 return false; 983 if (!this->jumpFalse(LabelFalse)) 984 return false; 985 986 if (!this->visitBool(RHS)) 987 return false; 988 if (!this->jump(LabelEnd)) 989 return false; 990 991 this->emitLabel(LabelFalse); 992 this->emitConstBool(false, E); 993 this->fallthrough(LabelEnd); 994 this->emitLabel(LabelEnd); 995 } 996 997 if (DiscardResult) 998 return this->emitPopBool(E); 999 1000 // For C, cast back to integer type. 1001 assert(T); 1002 if (T != PT_Bool) 1003 return this->emitCast(PT_Bool, *T, E); 1004 return true; 1005 } 1006 1007 template <class Emitter> 1008 bool Compiler<Emitter>::VisitComplexBinOp(const BinaryOperator *E) { 1009 // Prepare storage for result. 1010 if (!Initializing) { 1011 unsigned LocalIndex = allocateTemporary(E); 1012 if (!this->emitGetPtrLocal(LocalIndex, E)) 1013 return false; 1014 } 1015 1016 // Both LHS and RHS might _not_ be of complex type, but one of them 1017 // needs to be. 1018 const Expr *LHS = E->getLHS(); 1019 const Expr *RHS = E->getRHS(); 1020 1021 PrimType ResultElemT = this->classifyComplexElementType(E->getType()); 1022 unsigned ResultOffset = ~0u; 1023 if (!DiscardResult) 1024 ResultOffset = this->allocateLocalPrimitive(E, PT_Ptr, true, false); 1025 1026 // Save result pointer in ResultOffset 1027 if (!this->DiscardResult) { 1028 if (!this->emitDupPtr(E)) 1029 return false; 1030 if (!this->emitSetLocal(PT_Ptr, ResultOffset, E)) 1031 return false; 1032 } 1033 QualType LHSType = LHS->getType(); 1034 if (const auto *AT = LHSType->getAs<AtomicType>()) 1035 LHSType = AT->getValueType(); 1036 QualType RHSType = RHS->getType(); 1037 if (const auto *AT = RHSType->getAs<AtomicType>()) 1038 RHSType = AT->getValueType(); 1039 1040 bool LHSIsComplex = LHSType->isAnyComplexType(); 1041 unsigned LHSOffset; 1042 bool RHSIsComplex = RHSType->isAnyComplexType(); 1043 1044 // For ComplexComplex Mul, we have special ops to make their implementation 1045 // easier. 1046 BinaryOperatorKind Op = E->getOpcode(); 1047 if (Op == BO_Mul && LHSIsComplex && RHSIsComplex) { 1048 assert(classifyPrim(LHSType->getAs<ComplexType>()->getElementType()) == 1049 classifyPrim(RHSType->getAs<ComplexType>()->getElementType())); 1050 PrimType ElemT = 1051 classifyPrim(LHSType->getAs<ComplexType>()->getElementType()); 1052 if (!this->visit(LHS)) 1053 return false; 1054 if (!this->visit(RHS)) 1055 return false; 1056 return this->emitMulc(ElemT, E); 1057 } 1058 1059 if (Op == BO_Div && RHSIsComplex) { 1060 QualType ElemQT = RHSType->getAs<ComplexType>()->getElementType(); 1061 PrimType ElemT = classifyPrim(ElemQT); 1062 // If the LHS is not complex, we still need to do the full complex 1063 // division, so just stub create a complex value and stub it out with 1064 // the LHS and a zero. 1065 1066 if (!LHSIsComplex) { 1067 // This is using the RHS type for the fake-complex LHS. 1068 LHSOffset = allocateTemporary(RHS); 1069 1070 if (!this->emitGetPtrLocal(LHSOffset, E)) 1071 return false; 1072 1073 if (!this->visit(LHS)) 1074 return false; 1075 // real is LHS 1076 if (!this->emitInitElem(ElemT, 0, E)) 1077 return false; 1078 // imag is zero 1079 if (!this->visitZeroInitializer(ElemT, ElemQT, E)) 1080 return false; 1081 if (!this->emitInitElem(ElemT, 1, E)) 1082 return false; 1083 } else { 1084 if (!this->visit(LHS)) 1085 return false; 1086 } 1087 1088 if (!this->visit(RHS)) 1089 return false; 1090 return this->emitDivc(ElemT, E); 1091 } 1092 1093 // Evaluate LHS and save value to LHSOffset. 1094 if (LHSType->isAnyComplexType()) { 1095 LHSOffset = this->allocateLocalPrimitive(LHS, PT_Ptr, true, false); 1096 if (!this->visit(LHS)) 1097 return false; 1098 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E)) 1099 return false; 1100 } else { 1101 PrimType LHST = classifyPrim(LHSType); 1102 LHSOffset = this->allocateLocalPrimitive(LHS, LHST, true, false); 1103 if (!this->visit(LHS)) 1104 return false; 1105 if (!this->emitSetLocal(LHST, LHSOffset, E)) 1106 return false; 1107 } 1108 1109 // Same with RHS. 1110 unsigned RHSOffset; 1111 if (RHSType->isAnyComplexType()) { 1112 RHSOffset = this->allocateLocalPrimitive(RHS, PT_Ptr, true, false); 1113 if (!this->visit(RHS)) 1114 return false; 1115 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E)) 1116 return false; 1117 } else { 1118 PrimType RHST = classifyPrim(RHSType); 1119 RHSOffset = this->allocateLocalPrimitive(RHS, RHST, true, false); 1120 if (!this->visit(RHS)) 1121 return false; 1122 if (!this->emitSetLocal(RHST, RHSOffset, E)) 1123 return false; 1124 } 1125 1126 // For both LHS and RHS, either load the value from the complex pointer, or 1127 // directly from the local variable. For index 1 (i.e. the imaginary part), 1128 // just load 0 and do the operation anyway. 1129 auto loadComplexValue = [this](bool IsComplex, bool LoadZero, 1130 unsigned ElemIndex, unsigned Offset, 1131 const Expr *E) -> bool { 1132 if (IsComplex) { 1133 if (!this->emitGetLocal(PT_Ptr, Offset, E)) 1134 return false; 1135 return this->emitArrayElemPop(classifyComplexElementType(E->getType()), 1136 ElemIndex, E); 1137 } 1138 if (ElemIndex == 0 || !LoadZero) 1139 return this->emitGetLocal(classifyPrim(E->getType()), Offset, E); 1140 return this->visitZeroInitializer(classifyPrim(E->getType()), E->getType(), 1141 E); 1142 }; 1143 1144 // Now we can get pointers to the LHS and RHS from the offsets above. 1145 for (unsigned ElemIndex = 0; ElemIndex != 2; ++ElemIndex) { 1146 // Result pointer for the store later. 1147 if (!this->DiscardResult) { 1148 if (!this->emitGetLocal(PT_Ptr, ResultOffset, E)) 1149 return false; 1150 } 1151 1152 // The actual operation. 1153 switch (Op) { 1154 case BO_Add: 1155 if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS)) 1156 return false; 1157 1158 if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS)) 1159 return false; 1160 if (ResultElemT == PT_Float) { 1161 if (!this->emitAddf(getRoundingMode(E), E)) 1162 return false; 1163 } else { 1164 if (!this->emitAdd(ResultElemT, E)) 1165 return false; 1166 } 1167 break; 1168 case BO_Sub: 1169 if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS)) 1170 return false; 1171 1172 if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS)) 1173 return false; 1174 if (ResultElemT == PT_Float) { 1175 if (!this->emitSubf(getRoundingMode(E), E)) 1176 return false; 1177 } else { 1178 if (!this->emitSub(ResultElemT, E)) 1179 return false; 1180 } 1181 break; 1182 case BO_Mul: 1183 if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS)) 1184 return false; 1185 1186 if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS)) 1187 return false; 1188 1189 if (ResultElemT == PT_Float) { 1190 if (!this->emitMulf(getRoundingMode(E), E)) 1191 return false; 1192 } else { 1193 if (!this->emitMul(ResultElemT, E)) 1194 return false; 1195 } 1196 break; 1197 case BO_Div: 1198 assert(!RHSIsComplex); 1199 if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS)) 1200 return false; 1201 1202 if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS)) 1203 return false; 1204 1205 if (ResultElemT == PT_Float) { 1206 if (!this->emitDivf(getRoundingMode(E), E)) 1207 return false; 1208 } else { 1209 if (!this->emitDiv(ResultElemT, E)) 1210 return false; 1211 } 1212 break; 1213 1214 default: 1215 return false; 1216 } 1217 1218 if (!this->DiscardResult) { 1219 // Initialize array element with the value we just computed. 1220 if (!this->emitInitElemPop(ResultElemT, ElemIndex, E)) 1221 return false; 1222 } else { 1223 if (!this->emitPop(ResultElemT, E)) 1224 return false; 1225 } 1226 } 1227 return true; 1228 } 1229 1230 template <class Emitter> 1231 bool Compiler<Emitter>::VisitImplicitValueInitExpr( 1232 const ImplicitValueInitExpr *E) { 1233 QualType QT = E->getType(); 1234 1235 if (std::optional<PrimType> T = classify(QT)) 1236 return this->visitZeroInitializer(*T, QT, E); 1237 1238 if (QT->isRecordType()) { 1239 const RecordDecl *RD = QT->getAsRecordDecl(); 1240 assert(RD); 1241 if (RD->isInvalidDecl()) 1242 return false; 1243 if (RD->isUnion()) { 1244 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 1245 // object's first non-static named data member is zero-initialized 1246 // FIXME 1247 return false; 1248 } 1249 1250 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 1251 CXXRD && CXXRD->getNumVBases() > 0) { 1252 // TODO: Diagnose. 1253 return false; 1254 } 1255 1256 const Record *R = getRecord(QT); 1257 if (!R) 1258 return false; 1259 1260 assert(Initializing); 1261 return this->visitZeroRecordInitializer(R, E); 1262 } 1263 1264 if (QT->isIncompleteArrayType()) 1265 return true; 1266 1267 if (QT->isArrayType()) { 1268 const ArrayType *AT = QT->getAsArrayTypeUnsafe(); 1269 assert(AT); 1270 const auto *CAT = cast<ConstantArrayType>(AT); 1271 size_t NumElems = CAT->getZExtSize(); 1272 PrimType ElemT = classifyPrim(CAT->getElementType()); 1273 1274 for (size_t I = 0; I != NumElems; ++I) { 1275 if (!this->visitZeroInitializer(ElemT, CAT->getElementType(), E)) 1276 return false; 1277 if (!this->emitInitElem(ElemT, I, E)) 1278 return false; 1279 } 1280 1281 return true; 1282 } 1283 1284 if (const auto *ComplexTy = E->getType()->getAs<ComplexType>()) { 1285 assert(Initializing); 1286 QualType ElemQT = ComplexTy->getElementType(); 1287 PrimType ElemT = classifyPrim(ElemQT); 1288 for (unsigned I = 0; I < 2; ++I) { 1289 if (!this->visitZeroInitializer(ElemT, ElemQT, E)) 1290 return false; 1291 if (!this->emitInitElem(ElemT, I, E)) 1292 return false; 1293 } 1294 return true; 1295 } 1296 1297 if (const auto *VecT = E->getType()->getAs<VectorType>()) { 1298 unsigned NumVecElements = VecT->getNumElements(); 1299 QualType ElemQT = VecT->getElementType(); 1300 PrimType ElemT = classifyPrim(ElemQT); 1301 1302 for (unsigned I = 0; I < NumVecElements; ++I) { 1303 if (!this->visitZeroInitializer(ElemT, ElemQT, E)) 1304 return false; 1305 if (!this->emitInitElem(ElemT, I, E)) 1306 return false; 1307 } 1308 return true; 1309 } 1310 1311 return false; 1312 } 1313 1314 template <class Emitter> 1315 bool Compiler<Emitter>::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 1316 const Expr *LHS = E->getLHS(); 1317 const Expr *RHS = E->getRHS(); 1318 const Expr *Index = E->getIdx(); 1319 1320 if (DiscardResult) 1321 return this->discard(LHS) && this->discard(RHS); 1322 1323 // C++17's rules require us to evaluate the LHS first, regardless of which 1324 // side is the base. 1325 bool Success = true; 1326 for (const Expr *SubExpr : {LHS, RHS}) { 1327 if (!this->visit(SubExpr)) 1328 Success = false; 1329 } 1330 1331 if (!Success) 1332 return false; 1333 1334 PrimType IndexT = classifyPrim(Index->getType()); 1335 // If the index is first, we need to change that. 1336 if (LHS == Index) { 1337 if (!this->emitFlip(PT_Ptr, IndexT, E)) 1338 return false; 1339 } 1340 1341 return this->emitArrayElemPtrPop(IndexT, E); 1342 } 1343 1344 template <class Emitter> 1345 bool Compiler<Emitter>::visitInitList(ArrayRef<const Expr *> Inits, 1346 const Expr *ArrayFiller, const Expr *E) { 1347 QualType QT = E->getType(); 1348 if (const auto *AT = QT->getAs<AtomicType>()) 1349 QT = AT->getValueType(); 1350 1351 if (QT->isVoidType()) { 1352 if (Inits.size() == 0) 1353 return true; 1354 return this->emitInvalid(E); 1355 } 1356 1357 // Handle discarding first. 1358 if (DiscardResult) { 1359 for (const Expr *Init : Inits) { 1360 if (!this->discard(Init)) 1361 return false; 1362 } 1363 return true; 1364 } 1365 1366 // Primitive values. 1367 if (std::optional<PrimType> T = classify(QT)) { 1368 assert(!DiscardResult); 1369 if (Inits.size() == 0) 1370 return this->visitZeroInitializer(*T, QT, E); 1371 assert(Inits.size() == 1); 1372 return this->delegate(Inits[0]); 1373 } 1374 1375 if (QT->isRecordType()) { 1376 const Record *R = getRecord(QT); 1377 1378 if (Inits.size() == 1 && E->getType() == Inits[0]->getType()) 1379 return this->delegate(Inits[0]); 1380 1381 auto initPrimitiveField = [=](const Record::Field *FieldToInit, 1382 const Expr *Init, PrimType T) -> bool { 1383 InitStackScope<Emitter> ISS(this, isa<CXXDefaultInitExpr>(Init)); 1384 if (!this->visit(Init)) 1385 return false; 1386 1387 if (FieldToInit->isBitField()) 1388 return this->emitInitBitField(T, FieldToInit, E); 1389 return this->emitInitField(T, FieldToInit->Offset, E); 1390 }; 1391 1392 auto initCompositeField = [=](const Record::Field *FieldToInit, 1393 const Expr *Init) -> bool { 1394 InitStackScope<Emitter> ISS(this, isa<CXXDefaultInitExpr>(Init)); 1395 InitLinkScope<Emitter> ILS(this, InitLink::Field(FieldToInit->Offset)); 1396 // Non-primitive case. Get a pointer to the field-to-initialize 1397 // on the stack and recurse into visitInitializer(). 1398 if (!this->emitGetPtrField(FieldToInit->Offset, Init)) 1399 return false; 1400 if (!this->visitInitializer(Init)) 1401 return false; 1402 return this->emitPopPtr(E); 1403 }; 1404 1405 if (R->isUnion()) { 1406 if (Inits.size() == 0) { 1407 if (!this->visitZeroRecordInitializer(R, E)) 1408 return false; 1409 } else { 1410 const Expr *Init = Inits[0]; 1411 const FieldDecl *FToInit = nullptr; 1412 if (const auto *ILE = dyn_cast<InitListExpr>(E)) 1413 FToInit = ILE->getInitializedFieldInUnion(); 1414 else 1415 FToInit = cast<CXXParenListInitExpr>(E)->getInitializedFieldInUnion(); 1416 1417 const Record::Field *FieldToInit = R->getField(FToInit); 1418 if (std::optional<PrimType> T = classify(Init)) { 1419 if (!initPrimitiveField(FieldToInit, Init, *T)) 1420 return false; 1421 } else { 1422 if (!initCompositeField(FieldToInit, Init)) 1423 return false; 1424 } 1425 } 1426 return this->emitFinishInit(E); 1427 } 1428 1429 assert(!R->isUnion()); 1430 unsigned InitIndex = 0; 1431 for (const Expr *Init : Inits) { 1432 // Skip unnamed bitfields. 1433 while (InitIndex < R->getNumFields() && 1434 R->getField(InitIndex)->Decl->isUnnamedBitField()) 1435 ++InitIndex; 1436 1437 if (std::optional<PrimType> T = classify(Init)) { 1438 const Record::Field *FieldToInit = R->getField(InitIndex); 1439 if (!initPrimitiveField(FieldToInit, Init, *T)) 1440 return false; 1441 ++InitIndex; 1442 } else { 1443 // Initializer for a direct base class. 1444 if (const Record::Base *B = R->getBase(Init->getType())) { 1445 if (!this->emitGetPtrBase(B->Offset, Init)) 1446 return false; 1447 1448 if (!this->visitInitializer(Init)) 1449 return false; 1450 1451 if (!this->emitFinishInitPop(E)) 1452 return false; 1453 // Base initializers don't increase InitIndex, since they don't count 1454 // into the Record's fields. 1455 } else { 1456 const Record::Field *FieldToInit = R->getField(InitIndex); 1457 if (!initCompositeField(FieldToInit, Init)) 1458 return false; 1459 ++InitIndex; 1460 } 1461 } 1462 } 1463 return this->emitFinishInit(E); 1464 } 1465 1466 if (QT->isArrayType()) { 1467 if (Inits.size() == 1 && QT == Inits[0]->getType()) 1468 return this->delegate(Inits[0]); 1469 1470 unsigned ElementIndex = 0; 1471 for (const Expr *Init : Inits) { 1472 if (const auto *EmbedS = 1473 dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) { 1474 PrimType TargetT = classifyPrim(Init->getType()); 1475 1476 auto Eval = [&](const Expr *Init, unsigned ElemIndex) { 1477 PrimType InitT = classifyPrim(Init->getType()); 1478 if (!this->visit(Init)) 1479 return false; 1480 if (InitT != TargetT) { 1481 if (!this->emitCast(InitT, TargetT, E)) 1482 return false; 1483 } 1484 return this->emitInitElem(TargetT, ElemIndex, Init); 1485 }; 1486 if (!EmbedS->doForEachDataElement(Eval, ElementIndex)) 1487 return false; 1488 } else { 1489 if (!this->visitArrayElemInit(ElementIndex, Init)) 1490 return false; 1491 ++ElementIndex; 1492 } 1493 } 1494 1495 // Expand the filler expression. 1496 // FIXME: This should go away. 1497 if (ArrayFiller) { 1498 const ConstantArrayType *CAT = 1499 Ctx.getASTContext().getAsConstantArrayType(QT); 1500 uint64_t NumElems = CAT->getZExtSize(); 1501 1502 for (; ElementIndex != NumElems; ++ElementIndex) { 1503 if (!this->visitArrayElemInit(ElementIndex, ArrayFiller)) 1504 return false; 1505 } 1506 } 1507 1508 return this->emitFinishInit(E); 1509 } 1510 1511 if (const auto *ComplexTy = QT->getAs<ComplexType>()) { 1512 unsigned NumInits = Inits.size(); 1513 1514 if (NumInits == 1) 1515 return this->delegate(Inits[0]); 1516 1517 QualType ElemQT = ComplexTy->getElementType(); 1518 PrimType ElemT = classifyPrim(ElemQT); 1519 if (NumInits == 0) { 1520 // Zero-initialize both elements. 1521 for (unsigned I = 0; I < 2; ++I) { 1522 if (!this->visitZeroInitializer(ElemT, ElemQT, E)) 1523 return false; 1524 if (!this->emitInitElem(ElemT, I, E)) 1525 return false; 1526 } 1527 } else if (NumInits == 2) { 1528 unsigned InitIndex = 0; 1529 for (const Expr *Init : Inits) { 1530 if (!this->visit(Init)) 1531 return false; 1532 1533 if (!this->emitInitElem(ElemT, InitIndex, E)) 1534 return false; 1535 ++InitIndex; 1536 } 1537 } 1538 return true; 1539 } 1540 1541 if (const auto *VecT = QT->getAs<VectorType>()) { 1542 unsigned NumVecElements = VecT->getNumElements(); 1543 assert(NumVecElements >= Inits.size()); 1544 1545 QualType ElemQT = VecT->getElementType(); 1546 PrimType ElemT = classifyPrim(ElemQT); 1547 1548 // All initializer elements. 1549 unsigned InitIndex = 0; 1550 for (const Expr *Init : Inits) { 1551 if (!this->visit(Init)) 1552 return false; 1553 1554 // If the initializer is of vector type itself, we have to deconstruct 1555 // that and initialize all the target fields from the initializer fields. 1556 if (const auto *InitVecT = Init->getType()->getAs<VectorType>()) { 1557 if (!this->emitCopyArray(ElemT, 0, InitIndex, 1558 InitVecT->getNumElements(), E)) 1559 return false; 1560 InitIndex += InitVecT->getNumElements(); 1561 } else { 1562 if (!this->emitInitElem(ElemT, InitIndex, E)) 1563 return false; 1564 ++InitIndex; 1565 } 1566 } 1567 1568 assert(InitIndex <= NumVecElements); 1569 1570 // Fill the rest with zeroes. 1571 for (; InitIndex != NumVecElements; ++InitIndex) { 1572 if (!this->visitZeroInitializer(ElemT, ElemQT, E)) 1573 return false; 1574 if (!this->emitInitElem(ElemT, InitIndex, E)) 1575 return false; 1576 } 1577 return true; 1578 } 1579 1580 return false; 1581 } 1582 1583 /// Pointer to the array(not the element!) must be on the stack when calling 1584 /// this. 1585 template <class Emitter> 1586 bool Compiler<Emitter>::visitArrayElemInit(unsigned ElemIndex, 1587 const Expr *Init) { 1588 if (std::optional<PrimType> T = classify(Init->getType())) { 1589 // Visit the primitive element like normal. 1590 if (!this->visit(Init)) 1591 return false; 1592 return this->emitInitElem(*T, ElemIndex, Init); 1593 } 1594 1595 InitLinkScope<Emitter> ILS(this, InitLink::Elem(ElemIndex)); 1596 // Advance the pointer currently on the stack to the given 1597 // dimension. 1598 if (!this->emitConstUint32(ElemIndex, Init)) 1599 return false; 1600 if (!this->emitArrayElemPtrUint32(Init)) 1601 return false; 1602 if (!this->visitInitializer(Init)) 1603 return false; 1604 return this->emitFinishInitPop(Init); 1605 } 1606 1607 template <class Emitter> 1608 bool Compiler<Emitter>::VisitInitListExpr(const InitListExpr *E) { 1609 return this->visitInitList(E->inits(), E->getArrayFiller(), E); 1610 } 1611 1612 template <class Emitter> 1613 bool Compiler<Emitter>::VisitCXXParenListInitExpr( 1614 const CXXParenListInitExpr *E) { 1615 return this->visitInitList(E->getInitExprs(), E->getArrayFiller(), E); 1616 } 1617 1618 template <class Emitter> 1619 bool Compiler<Emitter>::VisitSubstNonTypeTemplateParmExpr( 1620 const SubstNonTypeTemplateParmExpr *E) { 1621 return this->delegate(E->getReplacement()); 1622 } 1623 1624 template <class Emitter> 1625 bool Compiler<Emitter>::VisitConstantExpr(const ConstantExpr *E) { 1626 std::optional<PrimType> T = classify(E->getType()); 1627 if (T && E->hasAPValueResult()) { 1628 // Try to emit the APValue directly, without visiting the subexpr. 1629 // This will only fail if we can't emit the APValue, so won't emit any 1630 // diagnostics or any double values. 1631 if (DiscardResult) 1632 return true; 1633 1634 if (this->visitAPValue(E->getAPValueResult(), *T, E)) 1635 return true; 1636 } 1637 return this->delegate(E->getSubExpr()); 1638 } 1639 1640 template <class Emitter> 1641 bool Compiler<Emitter>::VisitEmbedExpr(const EmbedExpr *E) { 1642 auto It = E->begin(); 1643 return this->visit(*It); 1644 } 1645 1646 static CharUnits AlignOfType(QualType T, const ASTContext &ASTCtx, 1647 UnaryExprOrTypeTrait Kind) { 1648 bool AlignOfReturnsPreferred = 1649 ASTCtx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 1650 1651 // C++ [expr.alignof]p3: 1652 // When alignof is applied to a reference type, the result is the 1653 // alignment of the referenced type. 1654 if (const auto *Ref = T->getAs<ReferenceType>()) 1655 T = Ref->getPointeeType(); 1656 1657 if (T.getQualifiers().hasUnaligned()) 1658 return CharUnits::One(); 1659 1660 // __alignof is defined to return the preferred alignment. 1661 // Before 8, clang returned the preferred alignment for alignof and 1662 // _Alignof as well. 1663 if (Kind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 1664 return ASTCtx.toCharUnitsFromBits(ASTCtx.getPreferredTypeAlign(T)); 1665 1666 return ASTCtx.getTypeAlignInChars(T); 1667 } 1668 1669 template <class Emitter> 1670 bool Compiler<Emitter>::VisitUnaryExprOrTypeTraitExpr( 1671 const UnaryExprOrTypeTraitExpr *E) { 1672 UnaryExprOrTypeTrait Kind = E->getKind(); 1673 const ASTContext &ASTCtx = Ctx.getASTContext(); 1674 1675 if (Kind == UETT_SizeOf || Kind == UETT_DataSizeOf) { 1676 QualType ArgType = E->getTypeOfArgument(); 1677 1678 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 1679 // the result is the size of the referenced type." 1680 if (const auto *Ref = ArgType->getAs<ReferenceType>()) 1681 ArgType = Ref->getPointeeType(); 1682 1683 CharUnits Size; 1684 if (ArgType->isVoidType() || ArgType->isFunctionType()) 1685 Size = CharUnits::One(); 1686 else { 1687 if (ArgType->isDependentType() || !ArgType->isConstantSizeType()) 1688 return false; 1689 1690 if (Kind == UETT_SizeOf) 1691 Size = ASTCtx.getTypeSizeInChars(ArgType); 1692 else 1693 Size = ASTCtx.getTypeInfoDataSizeInChars(ArgType).Width; 1694 } 1695 1696 if (DiscardResult) 1697 return true; 1698 1699 return this->emitConst(Size.getQuantity(), E); 1700 } 1701 1702 if (Kind == UETT_AlignOf || Kind == UETT_PreferredAlignOf) { 1703 CharUnits Size; 1704 1705 if (E->isArgumentType()) { 1706 QualType ArgType = E->getTypeOfArgument(); 1707 1708 Size = AlignOfType(ArgType, ASTCtx, Kind); 1709 } else { 1710 // Argument is an expression, not a type. 1711 const Expr *Arg = E->getArgumentExpr()->IgnoreParens(); 1712 1713 // The kinds of expressions that we have special-case logic here for 1714 // should be kept up to date with the special checks for those 1715 // expressions in Sema. 1716 1717 // alignof decl is always accepted, even if it doesn't make sense: we 1718 // default to 1 in those cases. 1719 if (const auto *DRE = dyn_cast<DeclRefExpr>(Arg)) 1720 Size = ASTCtx.getDeclAlign(DRE->getDecl(), 1721 /*RefAsPointee*/ true); 1722 else if (const auto *ME = dyn_cast<MemberExpr>(Arg)) 1723 Size = ASTCtx.getDeclAlign(ME->getMemberDecl(), 1724 /*RefAsPointee*/ true); 1725 else 1726 Size = AlignOfType(Arg->getType(), ASTCtx, Kind); 1727 } 1728 1729 if (DiscardResult) 1730 return true; 1731 1732 return this->emitConst(Size.getQuantity(), E); 1733 } 1734 1735 if (Kind == UETT_VectorElements) { 1736 if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>()) 1737 return this->emitConst(VT->getNumElements(), E); 1738 assert(E->getTypeOfArgument()->isSizelessVectorType()); 1739 return this->emitSizelessVectorElementSize(E); 1740 } 1741 1742 if (Kind == UETT_VecStep) { 1743 if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>()) { 1744 unsigned N = VT->getNumElements(); 1745 1746 // The vec_step built-in functions that take a 3-component 1747 // vector return 4. (OpenCL 1.1 spec 6.11.12) 1748 if (N == 3) 1749 N = 4; 1750 1751 return this->emitConst(N, E); 1752 } 1753 return this->emitConst(1, E); 1754 } 1755 1756 return false; 1757 } 1758 1759 template <class Emitter> 1760 bool Compiler<Emitter>::VisitMemberExpr(const MemberExpr *E) { 1761 // 'Base.Member' 1762 const Expr *Base = E->getBase(); 1763 const ValueDecl *Member = E->getMemberDecl(); 1764 1765 if (DiscardResult) 1766 return this->discard(Base); 1767 1768 // MemberExprs are almost always lvalues, in which case we don't need to 1769 // do the load. But sometimes they aren't. 1770 const auto maybeLoadValue = [&]() -> bool { 1771 if (E->isGLValue()) 1772 return true; 1773 if (std::optional<PrimType> T = classify(E)) 1774 return this->emitLoadPop(*T, E); 1775 return false; 1776 }; 1777 1778 if (const auto *VD = dyn_cast<VarDecl>(Member)) { 1779 // I am almost confident in saying that a var decl must be static 1780 // and therefore registered as a global variable. But this will probably 1781 // turn out to be wrong some time in the future, as always. 1782 if (auto GlobalIndex = P.getGlobal(VD)) 1783 return this->emitGetPtrGlobal(*GlobalIndex, E) && maybeLoadValue(); 1784 return false; 1785 } 1786 1787 if (!isa<FieldDecl>(Member)) 1788 return this->discard(Base) && this->visitDeclRef(Member, E); 1789 1790 if (Initializing) { 1791 if (!this->delegate(Base)) 1792 return false; 1793 } else { 1794 if (!this->visit(Base)) 1795 return false; 1796 } 1797 1798 // Base above gives us a pointer on the stack. 1799 const auto *FD = cast<FieldDecl>(Member); 1800 const RecordDecl *RD = FD->getParent(); 1801 const Record *R = getRecord(RD); 1802 if (!R) 1803 return false; 1804 const Record::Field *F = R->getField(FD); 1805 // Leave a pointer to the field on the stack. 1806 if (F->Decl->getType()->isReferenceType()) 1807 return this->emitGetFieldPop(PT_Ptr, F->Offset, E) && maybeLoadValue(); 1808 return this->emitGetPtrFieldPop(F->Offset, E) && maybeLoadValue(); 1809 } 1810 1811 template <class Emitter> 1812 bool Compiler<Emitter>::VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 1813 // ArrayIndex might not be set if a ArrayInitIndexExpr is being evaluated 1814 // stand-alone, e.g. via EvaluateAsInt(). 1815 if (!ArrayIndex) 1816 return false; 1817 return this->emitConst(*ArrayIndex, E); 1818 } 1819 1820 template <class Emitter> 1821 bool Compiler<Emitter>::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 1822 assert(Initializing); 1823 assert(!DiscardResult); 1824 1825 // We visit the common opaque expression here once so we have its value 1826 // cached. 1827 if (!this->discard(E->getCommonExpr())) 1828 return false; 1829 1830 // TODO: This compiles to quite a lot of bytecode if the array is larger. 1831 // Investigate compiling this to a loop. 1832 const Expr *SubExpr = E->getSubExpr(); 1833 size_t Size = E->getArraySize().getZExtValue(); 1834 1835 // So, every iteration, we execute an assignment here 1836 // where the LHS is on the stack (the target array) 1837 // and the RHS is our SubExpr. 1838 for (size_t I = 0; I != Size; ++I) { 1839 ArrayIndexScope<Emitter> IndexScope(this, I); 1840 BlockScope<Emitter> BS(this); 1841 1842 if (!this->visitArrayElemInit(I, SubExpr)) 1843 return false; 1844 if (!BS.destroyLocals()) 1845 return false; 1846 } 1847 return true; 1848 } 1849 1850 template <class Emitter> 1851 bool Compiler<Emitter>::VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 1852 const Expr *SourceExpr = E->getSourceExpr(); 1853 if (!SourceExpr) 1854 return false; 1855 1856 if (Initializing) 1857 return this->visitInitializer(SourceExpr); 1858 1859 PrimType SubExprT = classify(SourceExpr).value_or(PT_Ptr); 1860 if (auto It = OpaqueExprs.find(E); It != OpaqueExprs.end()) 1861 return this->emitGetLocal(SubExprT, It->second, E); 1862 1863 if (!this->visit(SourceExpr)) 1864 return false; 1865 1866 // At this point we either have the evaluated source expression or a pointer 1867 // to an object on the stack. We want to create a local variable that stores 1868 // this value. 1869 unsigned LocalIndex = allocateLocalPrimitive(E, SubExprT, /*IsConst=*/true); 1870 if (!this->emitSetLocal(SubExprT, LocalIndex, E)) 1871 return false; 1872 1873 // Here the local variable is created but the value is removed from the stack, 1874 // so we put it back if the caller needs it. 1875 if (!DiscardResult) { 1876 if (!this->emitGetLocal(SubExprT, LocalIndex, E)) 1877 return false; 1878 } 1879 1880 // This is cleaned up when the local variable is destroyed. 1881 OpaqueExprs.insert({E, LocalIndex}); 1882 1883 return true; 1884 } 1885 1886 template <class Emitter> 1887 bool Compiler<Emitter>::VisitAbstractConditionalOperator( 1888 const AbstractConditionalOperator *E) { 1889 const Expr *Condition = E->getCond(); 1890 const Expr *TrueExpr = E->getTrueExpr(); 1891 const Expr *FalseExpr = E->getFalseExpr(); 1892 1893 LabelTy LabelEnd = this->getLabel(); // Label after the operator. 1894 LabelTy LabelFalse = this->getLabel(); // Label for the false expr. 1895 1896 if (!this->visitBool(Condition)) 1897 return false; 1898 1899 if (!this->jumpFalse(LabelFalse)) 1900 return false; 1901 1902 { 1903 LocalScope<Emitter> S(this); 1904 if (!this->delegate(TrueExpr)) 1905 return false; 1906 if (!S.destroyLocals()) 1907 return false; 1908 } 1909 1910 if (!this->jump(LabelEnd)) 1911 return false; 1912 1913 this->emitLabel(LabelFalse); 1914 1915 { 1916 LocalScope<Emitter> S(this); 1917 if (!this->delegate(FalseExpr)) 1918 return false; 1919 if (!S.destroyLocals()) 1920 return false; 1921 } 1922 1923 this->fallthrough(LabelEnd); 1924 this->emitLabel(LabelEnd); 1925 1926 return true; 1927 } 1928 1929 template <class Emitter> 1930 bool Compiler<Emitter>::VisitStringLiteral(const StringLiteral *E) { 1931 if (DiscardResult) 1932 return true; 1933 1934 if (!Initializing) { 1935 unsigned StringIndex = P.createGlobalString(E); 1936 return this->emitGetPtrGlobal(StringIndex, E); 1937 } 1938 1939 // We are initializing an array on the stack. 1940 const ConstantArrayType *CAT = 1941 Ctx.getASTContext().getAsConstantArrayType(E->getType()); 1942 assert(CAT && "a string literal that's not a constant array?"); 1943 1944 // If the initializer string is too long, a diagnostic has already been 1945 // emitted. Read only the array length from the string literal. 1946 unsigned ArraySize = CAT->getZExtSize(); 1947 unsigned N = std::min(ArraySize, E->getLength()); 1948 size_t CharWidth = E->getCharByteWidth(); 1949 1950 for (unsigned I = 0; I != N; ++I) { 1951 uint32_t CodeUnit = E->getCodeUnit(I); 1952 1953 if (CharWidth == 1) { 1954 this->emitConstSint8(CodeUnit, E); 1955 this->emitInitElemSint8(I, E); 1956 } else if (CharWidth == 2) { 1957 this->emitConstUint16(CodeUnit, E); 1958 this->emitInitElemUint16(I, E); 1959 } else if (CharWidth == 4) { 1960 this->emitConstUint32(CodeUnit, E); 1961 this->emitInitElemUint32(I, E); 1962 } else { 1963 llvm_unreachable("unsupported character width"); 1964 } 1965 } 1966 1967 // Fill up the rest of the char array with NUL bytes. 1968 for (unsigned I = N; I != ArraySize; ++I) { 1969 if (CharWidth == 1) { 1970 this->emitConstSint8(0, E); 1971 this->emitInitElemSint8(I, E); 1972 } else if (CharWidth == 2) { 1973 this->emitConstUint16(0, E); 1974 this->emitInitElemUint16(I, E); 1975 } else if (CharWidth == 4) { 1976 this->emitConstUint32(0, E); 1977 this->emitInitElemUint32(I, E); 1978 } else { 1979 llvm_unreachable("unsupported character width"); 1980 } 1981 } 1982 1983 return true; 1984 } 1985 1986 template <class Emitter> 1987 bool Compiler<Emitter>::VisitObjCStringLiteral(const ObjCStringLiteral *E) { 1988 return this->delegate(E->getString()); 1989 } 1990 1991 template <class Emitter> 1992 bool Compiler<Emitter>::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { 1993 auto &A = Ctx.getASTContext(); 1994 std::string Str; 1995 A.getObjCEncodingForType(E->getEncodedType(), Str); 1996 StringLiteral *SL = 1997 StringLiteral::Create(A, Str, StringLiteralKind::Ordinary, 1998 /*Pascal=*/false, E->getType(), E->getAtLoc()); 1999 return this->delegate(SL); 2000 } 2001 2002 template <class Emitter> 2003 bool Compiler<Emitter>::VisitSYCLUniqueStableNameExpr( 2004 const SYCLUniqueStableNameExpr *E) { 2005 if (DiscardResult) 2006 return true; 2007 2008 assert(!Initializing); 2009 2010 auto &A = Ctx.getASTContext(); 2011 std::string ResultStr = E->ComputeName(A); 2012 2013 QualType CharTy = A.CharTy.withConst(); 2014 APInt Size(A.getTypeSize(A.getSizeType()), ResultStr.size() + 1); 2015 QualType ArrayTy = A.getConstantArrayType(CharTy, Size, nullptr, 2016 ArraySizeModifier::Normal, 0); 2017 2018 StringLiteral *SL = 2019 StringLiteral::Create(A, ResultStr, StringLiteralKind::Ordinary, 2020 /*Pascal=*/false, ArrayTy, E->getLocation()); 2021 2022 unsigned StringIndex = P.createGlobalString(SL); 2023 return this->emitGetPtrGlobal(StringIndex, E); 2024 } 2025 2026 template <class Emitter> 2027 bool Compiler<Emitter>::VisitCharacterLiteral(const CharacterLiteral *E) { 2028 if (DiscardResult) 2029 return true; 2030 return this->emitConst(E->getValue(), E); 2031 } 2032 2033 template <class Emitter> 2034 bool Compiler<Emitter>::VisitFloatCompoundAssignOperator( 2035 const CompoundAssignOperator *E) { 2036 2037 const Expr *LHS = E->getLHS(); 2038 const Expr *RHS = E->getRHS(); 2039 QualType LHSType = LHS->getType(); 2040 QualType LHSComputationType = E->getComputationLHSType(); 2041 QualType ResultType = E->getComputationResultType(); 2042 std::optional<PrimType> LT = classify(LHSComputationType); 2043 std::optional<PrimType> RT = classify(ResultType); 2044 2045 assert(ResultType->isFloatingType()); 2046 2047 if (!LT || !RT) 2048 return false; 2049 2050 PrimType LHST = classifyPrim(LHSType); 2051 2052 // C++17 onwards require that we evaluate the RHS first. 2053 // Compute RHS and save it in a temporary variable so we can 2054 // load it again later. 2055 if (!visit(RHS)) 2056 return false; 2057 2058 unsigned TempOffset = this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true); 2059 if (!this->emitSetLocal(*RT, TempOffset, E)) 2060 return false; 2061 2062 // First, visit LHS. 2063 if (!visit(LHS)) 2064 return false; 2065 if (!this->emitLoad(LHST, E)) 2066 return false; 2067 2068 // If necessary, convert LHS to its computation type. 2069 if (!this->emitPrimCast(LHST, classifyPrim(LHSComputationType), 2070 LHSComputationType, E)) 2071 return false; 2072 2073 // Now load RHS. 2074 if (!this->emitGetLocal(*RT, TempOffset, E)) 2075 return false; 2076 2077 llvm::RoundingMode RM = getRoundingMode(E); 2078 switch (E->getOpcode()) { 2079 case BO_AddAssign: 2080 if (!this->emitAddf(RM, E)) 2081 return false; 2082 break; 2083 case BO_SubAssign: 2084 if (!this->emitSubf(RM, E)) 2085 return false; 2086 break; 2087 case BO_MulAssign: 2088 if (!this->emitMulf(RM, E)) 2089 return false; 2090 break; 2091 case BO_DivAssign: 2092 if (!this->emitDivf(RM, E)) 2093 return false; 2094 break; 2095 default: 2096 return false; 2097 } 2098 2099 if (!this->emitPrimCast(classifyPrim(ResultType), LHST, LHS->getType(), E)) 2100 return false; 2101 2102 if (DiscardResult) 2103 return this->emitStorePop(LHST, E); 2104 return this->emitStore(LHST, E); 2105 } 2106 2107 template <class Emitter> 2108 bool Compiler<Emitter>::VisitPointerCompoundAssignOperator( 2109 const CompoundAssignOperator *E) { 2110 BinaryOperatorKind Op = E->getOpcode(); 2111 const Expr *LHS = E->getLHS(); 2112 const Expr *RHS = E->getRHS(); 2113 std::optional<PrimType> LT = classify(LHS->getType()); 2114 std::optional<PrimType> RT = classify(RHS->getType()); 2115 2116 if (Op != BO_AddAssign && Op != BO_SubAssign) 2117 return false; 2118 2119 if (!LT || !RT) 2120 return false; 2121 2122 if (!visit(LHS)) 2123 return false; 2124 2125 if (!this->emitLoad(*LT, LHS)) 2126 return false; 2127 2128 if (!visit(RHS)) 2129 return false; 2130 2131 if (Op == BO_AddAssign) { 2132 if (!this->emitAddOffset(*RT, E)) 2133 return false; 2134 } else { 2135 if (!this->emitSubOffset(*RT, E)) 2136 return false; 2137 } 2138 2139 if (DiscardResult) 2140 return this->emitStorePopPtr(E); 2141 return this->emitStorePtr(E); 2142 } 2143 2144 template <class Emitter> 2145 bool Compiler<Emitter>::VisitCompoundAssignOperator( 2146 const CompoundAssignOperator *E) { 2147 2148 const Expr *LHS = E->getLHS(); 2149 const Expr *RHS = E->getRHS(); 2150 std::optional<PrimType> LHSComputationT = 2151 classify(E->getComputationLHSType()); 2152 std::optional<PrimType> LT = classify(LHS->getType()); 2153 std::optional<PrimType> RT = classify(RHS->getType()); 2154 std::optional<PrimType> ResultT = classify(E->getType()); 2155 2156 if (!Ctx.getLangOpts().CPlusPlus14) 2157 return this->visit(RHS) && this->visit(LHS) && this->emitError(E); 2158 2159 if (!LT || !RT || !ResultT || !LHSComputationT) 2160 return false; 2161 2162 // Handle floating point operations separately here, since they 2163 // require special care. 2164 2165 if (ResultT == PT_Float || RT == PT_Float) 2166 return VisitFloatCompoundAssignOperator(E); 2167 2168 if (E->getType()->isPointerType()) 2169 return VisitPointerCompoundAssignOperator(E); 2170 2171 assert(!E->getType()->isPointerType() && "Handled above"); 2172 assert(!E->getType()->isFloatingType() && "Handled above"); 2173 2174 // C++17 onwards require that we evaluate the RHS first. 2175 // Compute RHS and save it in a temporary variable so we can 2176 // load it again later. 2177 // FIXME: Compound assignments are unsequenced in C, so we might 2178 // have to figure out how to reject them. 2179 if (!visit(RHS)) 2180 return false; 2181 2182 unsigned TempOffset = this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true); 2183 2184 if (!this->emitSetLocal(*RT, TempOffset, E)) 2185 return false; 2186 2187 // Get LHS pointer, load its value and cast it to the 2188 // computation type if necessary. 2189 if (!visit(LHS)) 2190 return false; 2191 if (!this->emitLoad(*LT, E)) 2192 return false; 2193 if (LT != LHSComputationT) { 2194 if (!this->emitCast(*LT, *LHSComputationT, E)) 2195 return false; 2196 } 2197 2198 // Get the RHS value on the stack. 2199 if (!this->emitGetLocal(*RT, TempOffset, E)) 2200 return false; 2201 2202 // Perform operation. 2203 switch (E->getOpcode()) { 2204 case BO_AddAssign: 2205 if (!this->emitAdd(*LHSComputationT, E)) 2206 return false; 2207 break; 2208 case BO_SubAssign: 2209 if (!this->emitSub(*LHSComputationT, E)) 2210 return false; 2211 break; 2212 case BO_MulAssign: 2213 if (!this->emitMul(*LHSComputationT, E)) 2214 return false; 2215 break; 2216 case BO_DivAssign: 2217 if (!this->emitDiv(*LHSComputationT, E)) 2218 return false; 2219 break; 2220 case BO_RemAssign: 2221 if (!this->emitRem(*LHSComputationT, E)) 2222 return false; 2223 break; 2224 case BO_ShlAssign: 2225 if (!this->emitShl(*LHSComputationT, *RT, E)) 2226 return false; 2227 break; 2228 case BO_ShrAssign: 2229 if (!this->emitShr(*LHSComputationT, *RT, E)) 2230 return false; 2231 break; 2232 case BO_AndAssign: 2233 if (!this->emitBitAnd(*LHSComputationT, E)) 2234 return false; 2235 break; 2236 case BO_XorAssign: 2237 if (!this->emitBitXor(*LHSComputationT, E)) 2238 return false; 2239 break; 2240 case BO_OrAssign: 2241 if (!this->emitBitOr(*LHSComputationT, E)) 2242 return false; 2243 break; 2244 default: 2245 llvm_unreachable("Unimplemented compound assign operator"); 2246 } 2247 2248 // And now cast from LHSComputationT to ResultT. 2249 if (ResultT != LHSComputationT) { 2250 if (!this->emitCast(*LHSComputationT, *ResultT, E)) 2251 return false; 2252 } 2253 2254 // And store the result in LHS. 2255 if (DiscardResult) { 2256 if (LHS->refersToBitField()) 2257 return this->emitStoreBitFieldPop(*ResultT, E); 2258 return this->emitStorePop(*ResultT, E); 2259 } 2260 if (LHS->refersToBitField()) 2261 return this->emitStoreBitField(*ResultT, E); 2262 return this->emitStore(*ResultT, E); 2263 } 2264 2265 template <class Emitter> 2266 bool Compiler<Emitter>::VisitExprWithCleanups(const ExprWithCleanups *E) { 2267 LocalScope<Emitter> ES(this); 2268 const Expr *SubExpr = E->getSubExpr(); 2269 2270 return this->delegate(SubExpr) && ES.destroyLocals(E); 2271 } 2272 2273 template <class Emitter> 2274 bool Compiler<Emitter>::VisitMaterializeTemporaryExpr( 2275 const MaterializeTemporaryExpr *E) { 2276 const Expr *SubExpr = E->getSubExpr(); 2277 2278 if (Initializing) { 2279 // We already have a value, just initialize that. 2280 return this->delegate(SubExpr); 2281 } 2282 // If we don't end up using the materialized temporary anyway, don't 2283 // bother creating it. 2284 if (DiscardResult) 2285 return this->discard(SubExpr); 2286 2287 // When we're initializing a global variable *or* the storage duration of 2288 // the temporary is explicitly static, create a global variable. 2289 std::optional<PrimType> SubExprT = classify(SubExpr); 2290 bool IsStatic = E->getStorageDuration() == SD_Static; 2291 if (IsStatic) { 2292 std::optional<unsigned> GlobalIndex = P.createGlobal(E); 2293 if (!GlobalIndex) 2294 return false; 2295 2296 const LifetimeExtendedTemporaryDecl *TempDecl = 2297 E->getLifetimeExtendedTemporaryDecl(); 2298 if (IsStatic) 2299 assert(TempDecl); 2300 2301 if (SubExprT) { 2302 if (!this->visit(SubExpr)) 2303 return false; 2304 if (IsStatic) { 2305 if (!this->emitInitGlobalTemp(*SubExprT, *GlobalIndex, TempDecl, E)) 2306 return false; 2307 } else { 2308 if (!this->emitInitGlobal(*SubExprT, *GlobalIndex, E)) 2309 return false; 2310 } 2311 return this->emitGetPtrGlobal(*GlobalIndex, E); 2312 } 2313 2314 // Non-primitive values. 2315 if (!this->emitGetPtrGlobal(*GlobalIndex, E)) 2316 return false; 2317 if (!this->visitInitializer(SubExpr)) 2318 return false; 2319 if (IsStatic) 2320 return this->emitInitGlobalTempComp(TempDecl, E); 2321 return true; 2322 } 2323 2324 // For everyhing else, use local variables. 2325 if (SubExprT) { 2326 unsigned LocalIndex = allocateLocalPrimitive( 2327 SubExpr, *SubExprT, /*IsConst=*/true, /*IsExtended=*/true); 2328 if (!this->visit(SubExpr)) 2329 return false; 2330 if (!this->emitSetLocal(*SubExprT, LocalIndex, E)) 2331 return false; 2332 return this->emitGetPtrLocal(LocalIndex, E); 2333 } else { 2334 const Expr *Inner = E->getSubExpr()->skipRValueSubobjectAdjustments(); 2335 if (std::optional<unsigned> LocalIndex = 2336 allocateLocal(Inner, E->getExtendingDecl())) { 2337 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex)); 2338 if (!this->emitGetPtrLocal(*LocalIndex, E)) 2339 return false; 2340 return this->visitInitializer(SubExpr); 2341 } 2342 } 2343 return false; 2344 } 2345 2346 template <class Emitter> 2347 bool Compiler<Emitter>::VisitCXXBindTemporaryExpr( 2348 const CXXBindTemporaryExpr *E) { 2349 return this->delegate(E->getSubExpr()); 2350 } 2351 2352 template <class Emitter> 2353 bool Compiler<Emitter>::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 2354 const Expr *Init = E->getInitializer(); 2355 if (DiscardResult) 2356 return this->discard(Init); 2357 2358 if (Initializing) { 2359 // We already have a value, just initialize that. 2360 return this->visitInitializer(Init) && this->emitFinishInit(E); 2361 } 2362 2363 std::optional<PrimType> T = classify(E->getType()); 2364 if (E->isFileScope()) { 2365 // Avoid creating a variable if this is a primitive RValue anyway. 2366 if (T && !E->isLValue()) 2367 return this->delegate(Init); 2368 2369 if (std::optional<unsigned> GlobalIndex = P.createGlobal(E)) { 2370 if (!this->emitGetPtrGlobal(*GlobalIndex, E)) 2371 return false; 2372 2373 if (T) { 2374 if (!this->visit(Init)) 2375 return false; 2376 return this->emitInitGlobal(*T, *GlobalIndex, E); 2377 } 2378 2379 return this->visitInitializer(Init) && this->emitFinishInit(E); 2380 } 2381 2382 return false; 2383 } 2384 2385 // Otherwise, use a local variable. 2386 if (T && !E->isLValue()) { 2387 // For primitive types, we just visit the initializer. 2388 return this->delegate(Init); 2389 } else { 2390 unsigned LocalIndex; 2391 2392 if (T) 2393 LocalIndex = this->allocateLocalPrimitive(Init, *T, false, false); 2394 else if (std::optional<unsigned> MaybeIndex = this->allocateLocal(Init)) 2395 LocalIndex = *MaybeIndex; 2396 else 2397 return false; 2398 2399 if (!this->emitGetPtrLocal(LocalIndex, E)) 2400 return false; 2401 2402 if (T) { 2403 if (!this->visit(Init)) { 2404 return false; 2405 } 2406 return this->emitInit(*T, E); 2407 } else { 2408 if (!this->visitInitializer(Init) || !this->emitFinishInit(E)) 2409 return false; 2410 } 2411 return true; 2412 } 2413 2414 return false; 2415 } 2416 2417 template <class Emitter> 2418 bool Compiler<Emitter>::VisitTypeTraitExpr(const TypeTraitExpr *E) { 2419 if (DiscardResult) 2420 return true; 2421 if (E->getType()->isBooleanType()) 2422 return this->emitConstBool(E->getValue(), E); 2423 return this->emitConst(E->getValue(), E); 2424 } 2425 2426 template <class Emitter> 2427 bool Compiler<Emitter>::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 2428 if (DiscardResult) 2429 return true; 2430 return this->emitConst(E->getValue(), E); 2431 } 2432 2433 template <class Emitter> 2434 bool Compiler<Emitter>::VisitLambdaExpr(const LambdaExpr *E) { 2435 if (DiscardResult) 2436 return true; 2437 2438 assert(Initializing); 2439 const Record *R = P.getOrCreateRecord(E->getLambdaClass()); 2440 2441 auto *CaptureInitIt = E->capture_init_begin(); 2442 // Initialize all fields (which represent lambda captures) of the 2443 // record with their initializers. 2444 for (const Record::Field &F : R->fields()) { 2445 const Expr *Init = *CaptureInitIt; 2446 ++CaptureInitIt; 2447 2448 if (!Init) 2449 continue; 2450 2451 if (std::optional<PrimType> T = classify(Init)) { 2452 if (!this->visit(Init)) 2453 return false; 2454 2455 if (!this->emitInitField(*T, F.Offset, E)) 2456 return false; 2457 } else { 2458 if (!this->emitGetPtrField(F.Offset, E)) 2459 return false; 2460 2461 if (!this->visitInitializer(Init)) 2462 return false; 2463 2464 if (!this->emitPopPtr(E)) 2465 return false; 2466 } 2467 } 2468 2469 return true; 2470 } 2471 2472 template <class Emitter> 2473 bool Compiler<Emitter>::VisitPredefinedExpr(const PredefinedExpr *E) { 2474 if (DiscardResult) 2475 return true; 2476 2477 return this->delegate(E->getFunctionName()); 2478 } 2479 2480 template <class Emitter> 2481 bool Compiler<Emitter>::VisitCXXThrowExpr(const CXXThrowExpr *E) { 2482 if (E->getSubExpr() && !this->discard(E->getSubExpr())) 2483 return false; 2484 2485 return this->emitInvalid(E); 2486 } 2487 2488 template <class Emitter> 2489 bool Compiler<Emitter>::VisitCXXReinterpretCastExpr( 2490 const CXXReinterpretCastExpr *E) { 2491 const Expr *SubExpr = E->getSubExpr(); 2492 2493 bool TypesMatch = classify(E) == classify(SubExpr); 2494 if (!this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/!TypesMatch, E)) 2495 return false; 2496 2497 return this->delegate(SubExpr); 2498 } 2499 2500 template <class Emitter> 2501 bool Compiler<Emitter>::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 2502 assert(E->getType()->isBooleanType()); 2503 2504 if (DiscardResult) 2505 return true; 2506 return this->emitConstBool(E->getValue(), E); 2507 } 2508 2509 template <class Emitter> 2510 bool Compiler<Emitter>::VisitCXXConstructExpr(const CXXConstructExpr *E) { 2511 QualType T = E->getType(); 2512 assert(!classify(T)); 2513 2514 if (T->isRecordType()) { 2515 const CXXConstructorDecl *Ctor = E->getConstructor(); 2516 2517 // Trivial copy/move constructor. Avoid copy. 2518 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() && 2519 Ctor->isTrivial() && 2520 E->getArg(0)->isTemporaryObject(Ctx.getASTContext(), 2521 T->getAsCXXRecordDecl())) 2522 return this->visitInitializer(E->getArg(0)); 2523 2524 // If we're discarding a construct expression, we still need 2525 // to allocate a variable and call the constructor and destructor. 2526 if (DiscardResult) { 2527 if (Ctor->isTrivial()) 2528 return true; 2529 assert(!Initializing); 2530 std::optional<unsigned> LocalIndex = allocateLocal(E); 2531 2532 if (!LocalIndex) 2533 return false; 2534 2535 if (!this->emitGetPtrLocal(*LocalIndex, E)) 2536 return false; 2537 } 2538 2539 // Zero initialization. 2540 if (E->requiresZeroInitialization()) { 2541 const Record *R = getRecord(E->getType()); 2542 2543 if (!this->visitZeroRecordInitializer(R, E)) 2544 return false; 2545 2546 // If the constructor is trivial anyway, we're done. 2547 if (Ctor->isTrivial()) 2548 return true; 2549 } 2550 2551 const Function *Func = getFunction(Ctor); 2552 2553 if (!Func) 2554 return false; 2555 2556 assert(Func->hasThisPointer()); 2557 assert(!Func->hasRVO()); 2558 2559 // The This pointer is already on the stack because this is an initializer, 2560 // but we need to dup() so the call() below has its own copy. 2561 if (!this->emitDupPtr(E)) 2562 return false; 2563 2564 // Constructor arguments. 2565 for (const auto *Arg : E->arguments()) { 2566 if (!this->visit(Arg)) 2567 return false; 2568 } 2569 2570 if (Func->isVariadic()) { 2571 uint32_t VarArgSize = 0; 2572 unsigned NumParams = Func->getNumWrittenParams(); 2573 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I) { 2574 VarArgSize += 2575 align(primSize(classify(E->getArg(I)->getType()).value_or(PT_Ptr))); 2576 } 2577 if (!this->emitCallVar(Func, VarArgSize, E)) 2578 return false; 2579 } else { 2580 if (!this->emitCall(Func, 0, E)) 2581 return false; 2582 } 2583 2584 if (DiscardResult) 2585 return this->emitPopPtr(E); 2586 return this->emitFinishInit(E); 2587 } 2588 2589 if (T->isArrayType()) { 2590 const ConstantArrayType *CAT = 2591 Ctx.getASTContext().getAsConstantArrayType(E->getType()); 2592 if (!CAT) 2593 return false; 2594 2595 size_t NumElems = CAT->getZExtSize(); 2596 const Function *Func = getFunction(E->getConstructor()); 2597 if (!Func || !Func->isConstexpr()) 2598 return false; 2599 2600 // FIXME(perf): We're calling the constructor once per array element here, 2601 // in the old intepreter we had a special-case for trivial constructors. 2602 for (size_t I = 0; I != NumElems; ++I) { 2603 if (!this->emitConstUint64(I, E)) 2604 return false; 2605 if (!this->emitArrayElemPtrUint64(E)) 2606 return false; 2607 2608 // Constructor arguments. 2609 for (const auto *Arg : E->arguments()) { 2610 if (!this->visit(Arg)) 2611 return false; 2612 } 2613 2614 if (!this->emitCall(Func, 0, E)) 2615 return false; 2616 } 2617 return true; 2618 } 2619 2620 return false; 2621 } 2622 2623 template <class Emitter> 2624 bool Compiler<Emitter>::VisitSourceLocExpr(const SourceLocExpr *E) { 2625 if (DiscardResult) 2626 return true; 2627 2628 const APValue Val = 2629 E->EvaluateInContext(Ctx.getASTContext(), SourceLocDefaultExpr); 2630 2631 // Things like __builtin_LINE(). 2632 if (E->getType()->isIntegerType()) { 2633 assert(Val.isInt()); 2634 const APSInt &I = Val.getInt(); 2635 return this->emitConst(I, E); 2636 } 2637 // Otherwise, the APValue is an LValue, with only one element. 2638 // Theoretically, we don't need the APValue at all of course. 2639 assert(E->getType()->isPointerType()); 2640 assert(Val.isLValue()); 2641 const APValue::LValueBase &Base = Val.getLValueBase(); 2642 if (const Expr *LValueExpr = Base.dyn_cast<const Expr *>()) 2643 return this->visit(LValueExpr); 2644 2645 // Otherwise, we have a decl (which is the case for 2646 // __builtin_source_location). 2647 assert(Base.is<const ValueDecl *>()); 2648 assert(Val.getLValuePath().size() == 0); 2649 const auto *BaseDecl = Base.dyn_cast<const ValueDecl *>(); 2650 assert(BaseDecl); 2651 2652 auto *UGCD = cast<UnnamedGlobalConstantDecl>(BaseDecl); 2653 2654 std::optional<unsigned> GlobalIndex = P.getOrCreateGlobal(UGCD); 2655 if (!GlobalIndex) 2656 return false; 2657 2658 if (!this->emitGetPtrGlobal(*GlobalIndex, E)) 2659 return false; 2660 2661 const Record *R = getRecord(E->getType()); 2662 const APValue &V = UGCD->getValue(); 2663 for (unsigned I = 0, N = R->getNumFields(); I != N; ++I) { 2664 const Record::Field *F = R->getField(I); 2665 const APValue &FieldValue = V.getStructField(I); 2666 2667 PrimType FieldT = classifyPrim(F->Decl->getType()); 2668 2669 if (!this->visitAPValue(FieldValue, FieldT, E)) 2670 return false; 2671 if (!this->emitInitField(FieldT, F->Offset, E)) 2672 return false; 2673 } 2674 2675 // Leave the pointer to the global on the stack. 2676 return true; 2677 } 2678 2679 template <class Emitter> 2680 bool Compiler<Emitter>::VisitOffsetOfExpr(const OffsetOfExpr *E) { 2681 unsigned N = E->getNumComponents(); 2682 if (N == 0) 2683 return false; 2684 2685 for (unsigned I = 0; I != N; ++I) { 2686 const OffsetOfNode &Node = E->getComponent(I); 2687 if (Node.getKind() == OffsetOfNode::Array) { 2688 const Expr *ArrayIndexExpr = E->getIndexExpr(Node.getArrayExprIndex()); 2689 PrimType IndexT = classifyPrim(ArrayIndexExpr->getType()); 2690 2691 if (DiscardResult) { 2692 if (!this->discard(ArrayIndexExpr)) 2693 return false; 2694 continue; 2695 } 2696 2697 if (!this->visit(ArrayIndexExpr)) 2698 return false; 2699 // Cast to Sint64. 2700 if (IndexT != PT_Sint64) { 2701 if (!this->emitCast(IndexT, PT_Sint64, E)) 2702 return false; 2703 } 2704 } 2705 } 2706 2707 if (DiscardResult) 2708 return true; 2709 2710 PrimType T = classifyPrim(E->getType()); 2711 return this->emitOffsetOf(T, E, E); 2712 } 2713 2714 template <class Emitter> 2715 bool Compiler<Emitter>::VisitCXXScalarValueInitExpr( 2716 const CXXScalarValueInitExpr *E) { 2717 QualType Ty = E->getType(); 2718 2719 if (DiscardResult || Ty->isVoidType()) 2720 return true; 2721 2722 if (std::optional<PrimType> T = classify(Ty)) 2723 return this->visitZeroInitializer(*T, Ty, E); 2724 2725 if (const auto *CT = Ty->getAs<ComplexType>()) { 2726 if (!Initializing) { 2727 std::optional<unsigned> LocalIndex = allocateLocal(E); 2728 if (!LocalIndex) 2729 return false; 2730 if (!this->emitGetPtrLocal(*LocalIndex, E)) 2731 return false; 2732 } 2733 2734 // Initialize both fields to 0. 2735 QualType ElemQT = CT->getElementType(); 2736 PrimType ElemT = classifyPrim(ElemQT); 2737 2738 for (unsigned I = 0; I != 2; ++I) { 2739 if (!this->visitZeroInitializer(ElemT, ElemQT, E)) 2740 return false; 2741 if (!this->emitInitElem(ElemT, I, E)) 2742 return false; 2743 } 2744 return true; 2745 } 2746 2747 if (const auto *VT = Ty->getAs<VectorType>()) { 2748 // FIXME: Code duplication with the _Complex case above. 2749 if (!Initializing) { 2750 std::optional<unsigned> LocalIndex = allocateLocal(E); 2751 if (!LocalIndex) 2752 return false; 2753 if (!this->emitGetPtrLocal(*LocalIndex, E)) 2754 return false; 2755 } 2756 2757 // Initialize all fields to 0. 2758 QualType ElemQT = VT->getElementType(); 2759 PrimType ElemT = classifyPrim(ElemQT); 2760 2761 for (unsigned I = 0, N = VT->getNumElements(); I != N; ++I) { 2762 if (!this->visitZeroInitializer(ElemT, ElemQT, E)) 2763 return false; 2764 if (!this->emitInitElem(ElemT, I, E)) 2765 return false; 2766 } 2767 return true; 2768 } 2769 2770 return false; 2771 } 2772 2773 template <class Emitter> 2774 bool Compiler<Emitter>::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 2775 return this->emitConst(E->getPackLength(), E); 2776 } 2777 2778 template <class Emitter> 2779 bool Compiler<Emitter>::VisitGenericSelectionExpr( 2780 const GenericSelectionExpr *E) { 2781 return this->delegate(E->getResultExpr()); 2782 } 2783 2784 template <class Emitter> 2785 bool Compiler<Emitter>::VisitChooseExpr(const ChooseExpr *E) { 2786 return this->delegate(E->getChosenSubExpr()); 2787 } 2788 2789 template <class Emitter> 2790 bool Compiler<Emitter>::VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 2791 if (DiscardResult) 2792 return true; 2793 2794 return this->emitConst(E->getValue(), E); 2795 } 2796 2797 template <class Emitter> 2798 bool Compiler<Emitter>::VisitCXXInheritedCtorInitExpr( 2799 const CXXInheritedCtorInitExpr *E) { 2800 const CXXConstructorDecl *Ctor = E->getConstructor(); 2801 assert(!Ctor->isTrivial() && 2802 "Trivial CXXInheritedCtorInitExpr, implement. (possible?)"); 2803 const Function *F = this->getFunction(Ctor); 2804 assert(F); 2805 assert(!F->hasRVO()); 2806 assert(F->hasThisPointer()); 2807 2808 if (!this->emitDupPtr(SourceInfo{})) 2809 return false; 2810 2811 // Forward all arguments of the current function (which should be a 2812 // constructor itself) to the inherited ctor. 2813 // This is necessary because the calling code has pushed the pointer 2814 // of the correct base for us already, but the arguments need 2815 // to come after. 2816 unsigned Offset = align(primSize(PT_Ptr)); // instance pointer. 2817 for (const ParmVarDecl *PD : Ctor->parameters()) { 2818 PrimType PT = this->classify(PD->getType()).value_or(PT_Ptr); 2819 2820 if (!this->emitGetParam(PT, Offset, E)) 2821 return false; 2822 Offset += align(primSize(PT)); 2823 } 2824 2825 return this->emitCall(F, 0, E); 2826 } 2827 2828 template <class Emitter> 2829 bool Compiler<Emitter>::VisitCXXNewExpr(const CXXNewExpr *E) { 2830 assert(classifyPrim(E->getType()) == PT_Ptr); 2831 const Expr *Init = E->getInitializer(); 2832 QualType ElementType = E->getAllocatedType(); 2833 std::optional<PrimType> ElemT = classify(ElementType); 2834 unsigned PlacementArgs = E->getNumPlacementArgs(); 2835 bool IsNoThrow = false; 2836 2837 // FIXME: Better diagnostic. diag::note_constexpr_new_placement 2838 if (PlacementArgs != 0) { 2839 // The only new-placement list we support is of the form (std::nothrow). 2840 // 2841 // FIXME: There is no restriction on this, but it's not clear that any 2842 // other form makes any sense. We get here for cases such as: 2843 // 2844 // new (std::align_val_t{N}) X(int) 2845 // 2846 // (which should presumably be valid only if N is a multiple of 2847 // alignof(int), and in any case can't be deallocated unless N is 2848 // alignof(X) and X has new-extended alignment). 2849 if (PlacementArgs != 1 || !E->getPlacementArg(0)->getType()->isNothrowT()) 2850 return this->emitInvalid(E); 2851 2852 if (!this->discard(E->getPlacementArg(0))) 2853 return false; 2854 IsNoThrow = true; 2855 } 2856 2857 const Descriptor *Desc; 2858 if (ElemT) { 2859 if (E->isArray()) 2860 Desc = nullptr; // We're not going to use it in this case. 2861 else 2862 Desc = P.createDescriptor(E, *ElemT, Descriptor::InlineDescMD, 2863 /*IsConst=*/false, /*IsTemporary=*/false, 2864 /*IsMutable=*/false); 2865 } else { 2866 Desc = P.createDescriptor( 2867 E, ElementType.getTypePtr(), 2868 E->isArray() ? std::nullopt : Descriptor::InlineDescMD, 2869 /*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false, Init); 2870 } 2871 2872 if (E->isArray()) { 2873 std::optional<const Expr *> ArraySizeExpr = E->getArraySize(); 2874 if (!ArraySizeExpr) 2875 return false; 2876 2877 const Expr *Stripped = *ArraySizeExpr; 2878 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 2879 Stripped = ICE->getSubExpr()) 2880 if (ICE->getCastKind() != CK_NoOp && 2881 ICE->getCastKind() != CK_IntegralCast) 2882 break; 2883 2884 PrimType SizeT = classifyPrim(Stripped->getType()); 2885 2886 if (!this->visit(Stripped)) 2887 return false; 2888 2889 if (ElemT) { 2890 // N primitive elements. 2891 if (!this->emitAllocN(SizeT, *ElemT, E, IsNoThrow, E)) 2892 return false; 2893 } else { 2894 // N Composite elements. 2895 if (!this->emitAllocCN(SizeT, Desc, IsNoThrow, E)) 2896 return false; 2897 } 2898 2899 if (Init && !this->visitInitializer(Init)) 2900 return false; 2901 2902 } else { 2903 // Allocate just one element. 2904 if (!this->emitAlloc(Desc, E)) 2905 return false; 2906 2907 if (Init) { 2908 if (ElemT) { 2909 if (!this->visit(Init)) 2910 return false; 2911 2912 if (!this->emitInit(*ElemT, E)) 2913 return false; 2914 } else { 2915 // Composite. 2916 if (!this->visitInitializer(Init)) 2917 return false; 2918 } 2919 } 2920 } 2921 2922 if (DiscardResult) 2923 return this->emitPopPtr(E); 2924 2925 return true; 2926 } 2927 2928 template <class Emitter> 2929 bool Compiler<Emitter>::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 2930 const Expr *Arg = E->getArgument(); 2931 2932 // Arg must be an lvalue. 2933 if (!this->visit(Arg)) 2934 return false; 2935 2936 return this->emitFree(E->isArrayForm(), E); 2937 } 2938 2939 template <class Emitter> 2940 bool Compiler<Emitter>::VisitBlockExpr(const BlockExpr *E) { 2941 const Function *Func = nullptr; 2942 if (auto F = Compiler<ByteCodeEmitter>(Ctx, P).compileObjCBlock(E)) 2943 Func = F; 2944 2945 if (!Func) 2946 return false; 2947 return this->emitGetFnPtr(Func, E); 2948 } 2949 2950 template <class Emitter> 2951 bool Compiler<Emitter>::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 2952 assert(Ctx.getLangOpts().CPlusPlus); 2953 return this->emitConstBool(E->getValue(), E); 2954 } 2955 2956 template <class Emitter> 2957 bool Compiler<Emitter>::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 2958 if (DiscardResult) 2959 return true; 2960 assert(!Initializing); 2961 2962 const MSGuidDecl *GuidDecl = E->getGuidDecl(); 2963 const RecordDecl *RD = GuidDecl->getType()->getAsRecordDecl(); 2964 assert(RD); 2965 // If the definiton of the result type is incomplete, just return a dummy. 2966 // If (and when) that is read from, we will fail, but not now. 2967 if (!RD->isCompleteDefinition()) { 2968 if (std::optional<unsigned> I = P.getOrCreateDummy(GuidDecl)) 2969 return this->emitGetPtrGlobal(*I, E); 2970 return false; 2971 } 2972 2973 std::optional<unsigned> GlobalIndex = P.getOrCreateGlobal(GuidDecl); 2974 if (!GlobalIndex) 2975 return false; 2976 if (!this->emitGetPtrGlobal(*GlobalIndex, E)) 2977 return false; 2978 2979 assert(this->getRecord(E->getType())); 2980 2981 const APValue &V = GuidDecl->getAsAPValue(); 2982 if (V.getKind() == APValue::None) 2983 return true; 2984 2985 assert(V.isStruct()); 2986 assert(V.getStructNumBases() == 0); 2987 if (!this->visitAPValueInitializer(V, E)) 2988 return false; 2989 2990 return this->emitFinishInit(E); 2991 } 2992 2993 template <class Emitter> 2994 bool Compiler<Emitter>::VisitRequiresExpr(const RequiresExpr *E) { 2995 assert(classifyPrim(E->getType()) == PT_Bool); 2996 if (DiscardResult) 2997 return true; 2998 return this->emitConstBool(E->isSatisfied(), E); 2999 } 3000 3001 template <class Emitter> 3002 bool Compiler<Emitter>::VisitConceptSpecializationExpr( 3003 const ConceptSpecializationExpr *E) { 3004 assert(classifyPrim(E->getType()) == PT_Bool); 3005 if (DiscardResult) 3006 return true; 3007 return this->emitConstBool(E->isSatisfied(), E); 3008 } 3009 3010 template <class Emitter> 3011 bool Compiler<Emitter>::VisitCXXRewrittenBinaryOperator( 3012 const CXXRewrittenBinaryOperator *E) { 3013 return this->delegate(E->getSemanticForm()); 3014 } 3015 3016 template <class Emitter> 3017 bool Compiler<Emitter>::VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 3018 3019 for (const Expr *SemE : E->semantics()) { 3020 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 3021 if (SemE == E->getResultExpr()) 3022 return false; 3023 3024 if (OVE->isUnique()) 3025 continue; 3026 3027 if (!this->discard(OVE)) 3028 return false; 3029 } else if (SemE == E->getResultExpr()) { 3030 if (!this->delegate(SemE)) 3031 return false; 3032 } else { 3033 if (!this->discard(SemE)) 3034 return false; 3035 } 3036 } 3037 return true; 3038 } 3039 3040 template <class Emitter> 3041 bool Compiler<Emitter>::VisitPackIndexingExpr(const PackIndexingExpr *E) { 3042 return this->delegate(E->getSelectedExpr()); 3043 } 3044 3045 template <class Emitter> 3046 bool Compiler<Emitter>::VisitRecoveryExpr(const RecoveryExpr *E) { 3047 return this->emitError(E); 3048 } 3049 3050 template <class Emitter> 3051 bool Compiler<Emitter>::VisitAddrLabelExpr(const AddrLabelExpr *E) { 3052 assert(E->getType()->isVoidPointerType()); 3053 3054 unsigned Offset = allocateLocalPrimitive( 3055 E->getLabel(), PT_Ptr, /*IsConst=*/true, /*IsExtended=*/false); 3056 3057 return this->emitGetLocal(PT_Ptr, Offset, E); 3058 } 3059 3060 template <class Emitter> 3061 bool Compiler<Emitter>::VisitConvertVectorExpr(const ConvertVectorExpr *E) { 3062 assert(Initializing); 3063 const auto *VT = E->getType()->castAs<VectorType>(); 3064 QualType ElemType = VT->getElementType(); 3065 PrimType ElemT = classifyPrim(ElemType); 3066 const Expr *Src = E->getSrcExpr(); 3067 PrimType SrcElemT = 3068 classifyPrim(Src->getType()->castAs<VectorType>()->getElementType()); 3069 3070 unsigned SrcOffset = this->allocateLocalPrimitive(Src, PT_Ptr, true, false); 3071 if (!this->visit(Src)) 3072 return false; 3073 if (!this->emitSetLocal(PT_Ptr, SrcOffset, E)) 3074 return false; 3075 3076 for (unsigned I = 0; I != VT->getNumElements(); ++I) { 3077 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E)) 3078 return false; 3079 if (!this->emitArrayElemPop(SrcElemT, I, E)) 3080 return false; 3081 if (SrcElemT != ElemT) { 3082 if (!this->emitPrimCast(SrcElemT, ElemT, ElemType, E)) 3083 return false; 3084 } 3085 if (!this->emitInitElem(ElemT, I, E)) 3086 return false; 3087 } 3088 3089 return true; 3090 } 3091 3092 template <class Emitter> 3093 bool Compiler<Emitter>::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) { 3094 assert(Initializing); 3095 assert(E->getNumSubExprs() > 2); 3096 3097 const Expr *Vecs[] = {E->getExpr(0), E->getExpr(1)}; 3098 const VectorType *VT = Vecs[0]->getType()->castAs<VectorType>(); 3099 PrimType ElemT = classifyPrim(VT->getElementType()); 3100 unsigned NumInputElems = VT->getNumElements(); 3101 unsigned NumOutputElems = E->getNumSubExprs() - 2; 3102 assert(NumOutputElems > 0); 3103 3104 // Save both input vectors to a local variable. 3105 unsigned VectorOffsets[2]; 3106 for (unsigned I = 0; I != 2; ++I) { 3107 VectorOffsets[I] = this->allocateLocalPrimitive( 3108 Vecs[I], PT_Ptr, /*IsConst=*/true, /*IsExtended=*/false); 3109 if (!this->visit(Vecs[I])) 3110 return false; 3111 if (!this->emitSetLocal(PT_Ptr, VectorOffsets[I], E)) 3112 return false; 3113 } 3114 for (unsigned I = 0; I != NumOutputElems; ++I) { 3115 APSInt ShuffleIndex = E->getShuffleMaskIdx(Ctx.getASTContext(), I); 3116 if (ShuffleIndex == -1) 3117 return this->emitInvalid(E); // FIXME: Better diagnostic. 3118 3119 assert(ShuffleIndex < (NumInputElems * 2)); 3120 if (!this->emitGetLocal(PT_Ptr, 3121 VectorOffsets[ShuffleIndex >= NumInputElems], E)) 3122 return false; 3123 unsigned InputVectorIndex = ShuffleIndex.getZExtValue() % NumInputElems; 3124 if (!this->emitArrayElemPop(ElemT, InputVectorIndex, E)) 3125 return false; 3126 3127 if (!this->emitInitElem(ElemT, I, E)) 3128 return false; 3129 } 3130 3131 return true; 3132 } 3133 3134 template <class Emitter> 3135 bool Compiler<Emitter>::VisitExtVectorElementExpr( 3136 const ExtVectorElementExpr *E) { 3137 const Expr *Base = E->getBase(); 3138 assert( 3139 Base->getType()->isVectorType() || 3140 Base->getType()->getAs<PointerType>()->getPointeeType()->isVectorType()); 3141 3142 SmallVector<uint32_t, 4> Indices; 3143 E->getEncodedElementAccess(Indices); 3144 3145 if (Indices.size() == 1) { 3146 if (!this->visit(Base)) 3147 return false; 3148 3149 if (E->isGLValue()) { 3150 if (!this->emitConstUint32(Indices[0], E)) 3151 return false; 3152 return this->emitArrayElemPtrPop(PT_Uint32, E); 3153 } 3154 // Else, also load the value. 3155 return this->emitArrayElemPop(classifyPrim(E->getType()), Indices[0], E); 3156 } 3157 3158 // Create a local variable for the base. 3159 unsigned BaseOffset = allocateLocalPrimitive(Base, PT_Ptr, /*IsConst=*/true, 3160 /*IsExtended=*/false); 3161 if (!this->visit(Base)) 3162 return false; 3163 if (!this->emitSetLocal(PT_Ptr, BaseOffset, E)) 3164 return false; 3165 3166 // Now the vector variable for the return value. 3167 if (!Initializing) { 3168 std::optional<unsigned> ResultIndex; 3169 ResultIndex = allocateLocal(E); 3170 if (!ResultIndex) 3171 return false; 3172 if (!this->emitGetPtrLocal(*ResultIndex, E)) 3173 return false; 3174 } 3175 3176 assert(Indices.size() == E->getType()->getAs<VectorType>()->getNumElements()); 3177 3178 PrimType ElemT = 3179 classifyPrim(E->getType()->getAs<VectorType>()->getElementType()); 3180 uint32_t DstIndex = 0; 3181 for (uint32_t I : Indices) { 3182 if (!this->emitGetLocal(PT_Ptr, BaseOffset, E)) 3183 return false; 3184 if (!this->emitArrayElemPop(ElemT, I, E)) 3185 return false; 3186 if (!this->emitInitElem(ElemT, DstIndex, E)) 3187 return false; 3188 ++DstIndex; 3189 } 3190 3191 // Leave the result pointer on the stack. 3192 assert(!DiscardResult); 3193 return true; 3194 } 3195 3196 template <class Emitter> 3197 bool Compiler<Emitter>::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 3198 const Expr *SubExpr = E->getSubExpr(); 3199 if (!E->isExpressibleAsConstantInitializer()) 3200 return this->discard(SubExpr) && this->emitInvalid(E); 3201 3202 return this->delegate(SubExpr); 3203 } 3204 3205 template <class Emitter> 3206 bool Compiler<Emitter>::VisitCXXStdInitializerListExpr( 3207 const CXXStdInitializerListExpr *E) { 3208 const Expr *SubExpr = E->getSubExpr(); 3209 const ConstantArrayType *ArrayType = 3210 Ctx.getASTContext().getAsConstantArrayType(SubExpr->getType()); 3211 const Record *R = getRecord(E->getType()); 3212 assert(Initializing); 3213 assert(SubExpr->isGLValue()); 3214 3215 if (!this->visit(SubExpr)) 3216 return false; 3217 if (!this->emitInitFieldPtr(R->getField(0u)->Offset, E)) 3218 return false; 3219 3220 PrimType SecondFieldT = classifyPrim(R->getField(1u)->Decl->getType()); 3221 if (isIntegralType(SecondFieldT)) { 3222 if (!this->emitConst(static_cast<APSInt>(ArrayType->getSize()), 3223 SecondFieldT, E)) 3224 return false; 3225 return this->emitInitField(SecondFieldT, R->getField(1u)->Offset, E); 3226 } 3227 assert(SecondFieldT == PT_Ptr); 3228 3229 if (!this->emitGetFieldPtr(R->getField(0u)->Offset, E)) 3230 return false; 3231 if (!this->emitConst(static_cast<APSInt>(ArrayType->getSize()), PT_Uint64, E)) 3232 return false; 3233 if (!this->emitArrayElemPtrPop(PT_Uint64, E)) 3234 return false; 3235 return this->emitInitFieldPtr(R->getField(1u)->Offset, E); 3236 } 3237 3238 template <class Emitter> 3239 bool Compiler<Emitter>::VisitStmtExpr(const StmtExpr *E) { 3240 BlockScope<Emitter> BS(this); 3241 StmtExprScope<Emitter> SS(this); 3242 3243 const CompoundStmt *CS = E->getSubStmt(); 3244 const Stmt *Result = CS->getStmtExprResult(); 3245 for (const Stmt *S : CS->body()) { 3246 if (S != Result) { 3247 if (!this->visitStmt(S)) 3248 return false; 3249 continue; 3250 } 3251 3252 assert(S == Result); 3253 if (const Expr *ResultExpr = dyn_cast<Expr>(S)) 3254 return this->delegate(ResultExpr); 3255 return this->emitUnsupported(E); 3256 } 3257 3258 return BS.destroyLocals(); 3259 } 3260 3261 template <class Emitter> bool Compiler<Emitter>::discard(const Expr *E) { 3262 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/true, 3263 /*NewInitializing=*/false); 3264 return this->Visit(E); 3265 } 3266 3267 template <class Emitter> bool Compiler<Emitter>::delegate(const Expr *E) { 3268 // We're basically doing: 3269 // OptionScope<Emitter> Scope(this, DicardResult, Initializing); 3270 // but that's unnecessary of course. 3271 return this->Visit(E); 3272 } 3273 3274 template <class Emitter> bool Compiler<Emitter>::visit(const Expr *E) { 3275 if (E->getType().isNull()) 3276 return false; 3277 3278 if (E->getType()->isVoidType()) 3279 return this->discard(E); 3280 3281 // Create local variable to hold the return value. 3282 if (!E->isGLValue() && !E->getType()->isAnyComplexType() && 3283 !classify(E->getType())) { 3284 std::optional<unsigned> LocalIndex = allocateLocal(E); 3285 if (!LocalIndex) 3286 return false; 3287 3288 if (!this->emitGetPtrLocal(*LocalIndex, E)) 3289 return false; 3290 return this->visitInitializer(E); 3291 } 3292 3293 // Otherwise,we have a primitive return value, produce the value directly 3294 // and push it on the stack. 3295 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false, 3296 /*NewInitializing=*/false); 3297 return this->Visit(E); 3298 } 3299 3300 template <class Emitter> 3301 bool Compiler<Emitter>::visitInitializer(const Expr *E) { 3302 assert(!classify(E->getType())); 3303 3304 if (!this->checkLiteralType(E)) 3305 return false; 3306 3307 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false, 3308 /*NewInitializing=*/true); 3309 return this->Visit(E); 3310 } 3311 3312 template <class Emitter> bool Compiler<Emitter>::visitBool(const Expr *E) { 3313 std::optional<PrimType> T = classify(E->getType()); 3314 if (!T) { 3315 // Convert complex values to bool. 3316 if (E->getType()->isAnyComplexType()) { 3317 if (!this->visit(E)) 3318 return false; 3319 return this->emitComplexBoolCast(E); 3320 } 3321 return false; 3322 } 3323 3324 if (!this->visit(E)) 3325 return false; 3326 3327 if (T == PT_Bool) 3328 return true; 3329 3330 // Convert pointers to bool. 3331 if (T == PT_Ptr || T == PT_FnPtr) { 3332 if (!this->emitNull(*T, nullptr, E)) 3333 return false; 3334 return this->emitNE(*T, E); 3335 } 3336 3337 // Or Floats. 3338 if (T == PT_Float) 3339 return this->emitCastFloatingIntegralBool(E); 3340 3341 // Or anything else we can. 3342 return this->emitCast(*T, PT_Bool, E); 3343 } 3344 3345 template <class Emitter> 3346 bool Compiler<Emitter>::visitZeroInitializer(PrimType T, QualType QT, 3347 const Expr *E) { 3348 switch (T) { 3349 case PT_Bool: 3350 return this->emitZeroBool(E); 3351 case PT_Sint8: 3352 return this->emitZeroSint8(E); 3353 case PT_Uint8: 3354 return this->emitZeroUint8(E); 3355 case PT_Sint16: 3356 return this->emitZeroSint16(E); 3357 case PT_Uint16: 3358 return this->emitZeroUint16(E); 3359 case PT_Sint32: 3360 return this->emitZeroSint32(E); 3361 case PT_Uint32: 3362 return this->emitZeroUint32(E); 3363 case PT_Sint64: 3364 return this->emitZeroSint64(E); 3365 case PT_Uint64: 3366 return this->emitZeroUint64(E); 3367 case PT_IntAP: 3368 return this->emitZeroIntAP(Ctx.getBitWidth(QT), E); 3369 case PT_IntAPS: 3370 return this->emitZeroIntAPS(Ctx.getBitWidth(QT), E); 3371 case PT_Ptr: 3372 return this->emitNullPtr(nullptr, E); 3373 case PT_FnPtr: 3374 return this->emitNullFnPtr(nullptr, E); 3375 case PT_MemberPtr: 3376 return this->emitNullMemberPtr(nullptr, E); 3377 case PT_Float: { 3378 return this->emitConstFloat(APFloat::getZero(Ctx.getFloatSemantics(QT)), E); 3379 } 3380 } 3381 llvm_unreachable("unknown primitive type"); 3382 } 3383 3384 template <class Emitter> 3385 bool Compiler<Emitter>::visitZeroRecordInitializer(const Record *R, 3386 const Expr *E) { 3387 assert(E); 3388 assert(R); 3389 // Fields 3390 for (const Record::Field &Field : R->fields()) { 3391 if (Field.Decl->isUnnamedBitField()) 3392 continue; 3393 3394 const Descriptor *D = Field.Desc; 3395 if (D->isPrimitive()) { 3396 QualType QT = D->getType(); 3397 PrimType T = classifyPrim(D->getType()); 3398 if (!this->visitZeroInitializer(T, QT, E)) 3399 return false; 3400 if (!this->emitInitField(T, Field.Offset, E)) 3401 return false; 3402 if (R->isUnion()) 3403 break; 3404 continue; 3405 } 3406 3407 if (!this->emitGetPtrField(Field.Offset, E)) 3408 return false; 3409 3410 if (D->isPrimitiveArray()) { 3411 QualType ET = D->getElemQualType(); 3412 PrimType T = classifyPrim(ET); 3413 for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) { 3414 if (!this->visitZeroInitializer(T, ET, E)) 3415 return false; 3416 if (!this->emitInitElem(T, I, E)) 3417 return false; 3418 } 3419 } else if (D->isCompositeArray()) { 3420 const Record *ElemRecord = D->ElemDesc->ElemRecord; 3421 assert(D->ElemDesc->ElemRecord); 3422 for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) { 3423 if (!this->emitConstUint32(I, E)) 3424 return false; 3425 if (!this->emitArrayElemPtr(PT_Uint32, E)) 3426 return false; 3427 if (!this->visitZeroRecordInitializer(ElemRecord, E)) 3428 return false; 3429 if (!this->emitPopPtr(E)) 3430 return false; 3431 } 3432 } else if (D->isRecord()) { 3433 if (!this->visitZeroRecordInitializer(D->ElemRecord, E)) 3434 return false; 3435 } else { 3436 assert(false); 3437 } 3438 3439 if (!this->emitFinishInitPop(E)) 3440 return false; 3441 3442 if (R->isUnion()) 3443 break; 3444 } 3445 3446 for (const Record::Base &B : R->bases()) { 3447 if (!this->emitGetPtrBase(B.Offset, E)) 3448 return false; 3449 if (!this->visitZeroRecordInitializer(B.R, E)) 3450 return false; 3451 if (!this->emitFinishInitPop(E)) 3452 return false; 3453 } 3454 3455 // FIXME: Virtual bases. 3456 3457 return true; 3458 } 3459 3460 template <class Emitter> 3461 template <typename T> 3462 bool Compiler<Emitter>::emitConst(T Value, PrimType Ty, const Expr *E) { 3463 switch (Ty) { 3464 case PT_Sint8: 3465 return this->emitConstSint8(Value, E); 3466 case PT_Uint8: 3467 return this->emitConstUint8(Value, E); 3468 case PT_Sint16: 3469 return this->emitConstSint16(Value, E); 3470 case PT_Uint16: 3471 return this->emitConstUint16(Value, E); 3472 case PT_Sint32: 3473 return this->emitConstSint32(Value, E); 3474 case PT_Uint32: 3475 return this->emitConstUint32(Value, E); 3476 case PT_Sint64: 3477 return this->emitConstSint64(Value, E); 3478 case PT_Uint64: 3479 return this->emitConstUint64(Value, E); 3480 case PT_Bool: 3481 return this->emitConstBool(Value, E); 3482 case PT_Ptr: 3483 case PT_FnPtr: 3484 case PT_MemberPtr: 3485 case PT_Float: 3486 case PT_IntAP: 3487 case PT_IntAPS: 3488 llvm_unreachable("Invalid integral type"); 3489 break; 3490 } 3491 llvm_unreachable("unknown primitive type"); 3492 } 3493 3494 template <class Emitter> 3495 template <typename T> 3496 bool Compiler<Emitter>::emitConst(T Value, const Expr *E) { 3497 return this->emitConst(Value, classifyPrim(E->getType()), E); 3498 } 3499 3500 template <class Emitter> 3501 bool Compiler<Emitter>::emitConst(const APSInt &Value, PrimType Ty, 3502 const Expr *E) { 3503 if (Ty == PT_IntAPS) 3504 return this->emitConstIntAPS(Value, E); 3505 if (Ty == PT_IntAP) 3506 return this->emitConstIntAP(Value, E); 3507 3508 if (Value.isSigned()) 3509 return this->emitConst(Value.getSExtValue(), Ty, E); 3510 return this->emitConst(Value.getZExtValue(), Ty, E); 3511 } 3512 3513 template <class Emitter> 3514 bool Compiler<Emitter>::emitConst(const APSInt &Value, const Expr *E) { 3515 return this->emitConst(Value, classifyPrim(E->getType()), E); 3516 } 3517 3518 template <class Emitter> 3519 unsigned Compiler<Emitter>::allocateLocalPrimitive(DeclTy &&Src, PrimType Ty, 3520 bool IsConst, 3521 bool IsExtended) { 3522 // Make sure we don't accidentally register the same decl twice. 3523 if (const auto *VD = 3524 dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) { 3525 assert(!P.getGlobal(VD)); 3526 assert(!Locals.contains(VD)); 3527 (void)VD; 3528 } 3529 3530 // FIXME: There are cases where Src.is<Expr*>() is wrong, e.g. 3531 // (int){12} in C. Consider using Expr::isTemporaryObject() instead 3532 // or isa<MaterializeTemporaryExpr>(). 3533 Descriptor *D = P.createDescriptor(Src, Ty, Descriptor::InlineDescMD, IsConst, 3534 Src.is<const Expr *>()); 3535 Scope::Local Local = this->createLocal(D); 3536 if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) 3537 Locals.insert({VD, Local}); 3538 VarScope->add(Local, IsExtended); 3539 return Local.Offset; 3540 } 3541 3542 template <class Emitter> 3543 std::optional<unsigned> 3544 Compiler<Emitter>::allocateLocal(DeclTy &&Src, const ValueDecl *ExtendingDecl) { 3545 // Make sure we don't accidentally register the same decl twice. 3546 if ([[maybe_unused]] const auto *VD = 3547 dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) { 3548 assert(!P.getGlobal(VD)); 3549 assert(!Locals.contains(VD)); 3550 } 3551 3552 QualType Ty; 3553 const ValueDecl *Key = nullptr; 3554 const Expr *Init = nullptr; 3555 bool IsTemporary = false; 3556 if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) { 3557 Key = VD; 3558 Ty = VD->getType(); 3559 3560 if (const auto *VarD = dyn_cast<VarDecl>(VD)) 3561 Init = VarD->getInit(); 3562 } 3563 if (auto *E = Src.dyn_cast<const Expr *>()) { 3564 IsTemporary = true; 3565 Ty = E->getType(); 3566 } 3567 3568 Descriptor *D = P.createDescriptor( 3569 Src, Ty.getTypePtr(), Descriptor::InlineDescMD, Ty.isConstQualified(), 3570 IsTemporary, /*IsMutable=*/false, Init); 3571 if (!D) 3572 return std::nullopt; 3573 3574 Scope::Local Local = this->createLocal(D); 3575 if (Key) 3576 Locals.insert({Key, Local}); 3577 if (ExtendingDecl) 3578 VarScope->addExtended(Local, ExtendingDecl); 3579 else 3580 VarScope->add(Local, false); 3581 return Local.Offset; 3582 } 3583 3584 template <class Emitter> 3585 unsigned Compiler<Emitter>::allocateTemporary(const Expr *E) { 3586 QualType Ty = E->getType(); 3587 assert(!Ty->isRecordType()); 3588 3589 Descriptor *D = P.createDescriptor( 3590 E, Ty.getTypePtr(), Descriptor::InlineDescMD, Ty.isConstQualified(), 3591 /*IsTemporary=*/true, /*IsMutable=*/false, /*Init=*/nullptr); 3592 assert(D); 3593 3594 Scope::Local Local = this->createLocal(D); 3595 VariableScope<Emitter> *S = VarScope; 3596 assert(S); 3597 // Attach to topmost scope. 3598 while (S->getParent()) 3599 S = S->getParent(); 3600 assert(S && !S->getParent()); 3601 S->addLocal(Local); 3602 return Local.Offset; 3603 } 3604 3605 template <class Emitter> 3606 const RecordType *Compiler<Emitter>::getRecordTy(QualType Ty) { 3607 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) 3608 return PT->getPointeeType()->getAs<RecordType>(); 3609 return Ty->getAs<RecordType>(); 3610 } 3611 3612 template <class Emitter> Record *Compiler<Emitter>::getRecord(QualType Ty) { 3613 if (const auto *RecordTy = getRecordTy(Ty)) 3614 return getRecord(RecordTy->getDecl()); 3615 return nullptr; 3616 } 3617 3618 template <class Emitter> 3619 Record *Compiler<Emitter>::getRecord(const RecordDecl *RD) { 3620 return P.getOrCreateRecord(RD); 3621 } 3622 3623 template <class Emitter> 3624 const Function *Compiler<Emitter>::getFunction(const FunctionDecl *FD) { 3625 return Ctx.getOrCreateFunction(FD); 3626 } 3627 3628 template <class Emitter> bool Compiler<Emitter>::visitExpr(const Expr *E) { 3629 LocalScope<Emitter> RootScope(this); 3630 // Void expressions. 3631 if (E->getType()->isVoidType()) { 3632 if (!visit(E)) 3633 return false; 3634 return this->emitRetVoid(E) && RootScope.destroyLocals(); 3635 } 3636 3637 // Expressions with a primitive return type. 3638 if (std::optional<PrimType> T = classify(E)) { 3639 if (!visit(E)) 3640 return false; 3641 return this->emitRet(*T, E) && RootScope.destroyLocals(); 3642 } 3643 3644 // Expressions with a composite return type. 3645 // For us, that means everything we don't 3646 // have a PrimType for. 3647 if (std::optional<unsigned> LocalOffset = this->allocateLocal(E)) { 3648 if (!this->emitGetPtrLocal(*LocalOffset, E)) 3649 return false; 3650 3651 if (!visitInitializer(E)) 3652 return false; 3653 3654 if (!this->emitFinishInit(E)) 3655 return false; 3656 // We are destroying the locals AFTER the Ret op. 3657 // The Ret op needs to copy the (alive) values, but the 3658 // destructors may still turn the entire expression invalid. 3659 return this->emitRetValue(E) && RootScope.destroyLocals(); 3660 } 3661 3662 RootScope.destroyLocals(); 3663 return false; 3664 } 3665 3666 template <class Emitter> 3667 VarCreationState Compiler<Emitter>::visitDecl(const VarDecl *VD) { 3668 3669 auto R = this->visitVarDecl(VD, /*Toplevel=*/true); 3670 3671 if (R.notCreated()) 3672 return R; 3673 3674 if (R) 3675 return true; 3676 3677 if (!R && Context::shouldBeGloballyIndexed(VD)) { 3678 if (auto GlobalIndex = P.getGlobal(VD)) { 3679 Block *GlobalBlock = P.getGlobal(*GlobalIndex); 3680 GlobalInlineDescriptor &GD = 3681 *reinterpret_cast<GlobalInlineDescriptor *>(GlobalBlock->rawData()); 3682 3683 GD.InitState = GlobalInitState::InitializerFailed; 3684 GlobalBlock->invokeDtor(); 3685 } 3686 } 3687 3688 return R; 3689 } 3690 3691 /// Toplevel visitDeclAndReturn(). 3692 /// We get here from evaluateAsInitializer(). 3693 /// We need to evaluate the initializer and return its value. 3694 template <class Emitter> 3695 bool Compiler<Emitter>::visitDeclAndReturn(const VarDecl *VD, 3696 bool ConstantContext) { 3697 std::optional<PrimType> VarT = classify(VD->getType()); 3698 3699 // We only create variables if we're evaluating in a constant context. 3700 // Otherwise, just evaluate the initializer and return it. 3701 if (!ConstantContext) { 3702 DeclScope<Emitter> LS(this, VD); 3703 if (!this->visit(VD->getAnyInitializer())) 3704 return false; 3705 return this->emitRet(VarT.value_or(PT_Ptr), VD) && LS.destroyLocals(); 3706 } 3707 3708 LocalScope<Emitter> VDScope(this, VD); 3709 if (!this->visitVarDecl(VD, /*Toplevel=*/true)) 3710 return false; 3711 3712 if (Context::shouldBeGloballyIndexed(VD)) { 3713 auto GlobalIndex = P.getGlobal(VD); 3714 assert(GlobalIndex); // visitVarDecl() didn't return false. 3715 if (VarT) { 3716 if (!this->emitGetGlobalUnchecked(*VarT, *GlobalIndex, VD)) 3717 return false; 3718 } else { 3719 if (!this->emitGetPtrGlobal(*GlobalIndex, VD)) 3720 return false; 3721 } 3722 } else { 3723 auto Local = Locals.find(VD); 3724 assert(Local != Locals.end()); // Same here. 3725 if (VarT) { 3726 if (!this->emitGetLocal(*VarT, Local->second.Offset, VD)) 3727 return false; 3728 } else { 3729 if (!this->emitGetPtrLocal(Local->second.Offset, VD)) 3730 return false; 3731 } 3732 } 3733 3734 // Return the value. 3735 if (!this->emitRet(VarT.value_or(PT_Ptr), VD)) { 3736 // If the Ret above failed and this is a global variable, mark it as 3737 // uninitialized, even everything else succeeded. 3738 if (Context::shouldBeGloballyIndexed(VD)) { 3739 auto GlobalIndex = P.getGlobal(VD); 3740 assert(GlobalIndex); 3741 Block *GlobalBlock = P.getGlobal(*GlobalIndex); 3742 GlobalInlineDescriptor &GD = 3743 *reinterpret_cast<GlobalInlineDescriptor *>(GlobalBlock->rawData()); 3744 3745 GD.InitState = GlobalInitState::InitializerFailed; 3746 GlobalBlock->invokeDtor(); 3747 } 3748 return false; 3749 } 3750 3751 return VDScope.destroyLocals(); 3752 } 3753 3754 template <class Emitter> 3755 VarCreationState Compiler<Emitter>::visitVarDecl(const VarDecl *VD, 3756 bool Toplevel) { 3757 // We don't know what to do with these, so just return false. 3758 if (VD->getType().isNull()) 3759 return false; 3760 3761 // This case is EvalEmitter-only. If we won't create any instructions for the 3762 // initializer anyway, don't bother creating the variable in the first place. 3763 if (!this->isActive()) 3764 return VarCreationState::NotCreated(); 3765 3766 const Expr *Init = VD->getInit(); 3767 std::optional<PrimType> VarT = classify(VD->getType()); 3768 3769 if (Init && Init->isValueDependent()) 3770 return false; 3771 3772 if (Context::shouldBeGloballyIndexed(VD)) { 3773 auto checkDecl = [&]() -> bool { 3774 bool NeedsOp = !Toplevel && VD->isLocalVarDecl() && VD->isStaticLocal(); 3775 return !NeedsOp || this->emitCheckDecl(VD, VD); 3776 }; 3777 3778 auto initGlobal = [&](unsigned GlobalIndex) -> bool { 3779 assert(Init); 3780 DeclScope<Emitter> LocalScope(this, VD); 3781 3782 if (VarT) { 3783 if (!this->visit(Init)) 3784 return checkDecl() && false; 3785 3786 return checkDecl() && this->emitInitGlobal(*VarT, GlobalIndex, VD); 3787 } 3788 3789 if (!checkDecl()) 3790 return false; 3791 3792 if (!this->emitGetPtrGlobal(GlobalIndex, Init)) 3793 return false; 3794 3795 if (!visitInitializer(Init)) 3796 return false; 3797 3798 if (!this->emitFinishInit(Init)) 3799 return false; 3800 3801 return this->emitPopPtr(Init); 3802 }; 3803 3804 // We've already seen and initialized this global. 3805 if (std::optional<unsigned> GlobalIndex = P.getGlobal(VD)) { 3806 if (P.getPtrGlobal(*GlobalIndex).isInitialized()) 3807 return checkDecl(); 3808 3809 // The previous attempt at initialization might've been unsuccessful, 3810 // so let's try this one. 3811 return Init && checkDecl() && initGlobal(*GlobalIndex); 3812 } 3813 3814 std::optional<unsigned> GlobalIndex = P.createGlobal(VD, Init); 3815 3816 if (!GlobalIndex) 3817 return false; 3818 3819 return !Init || (checkDecl() && initGlobal(*GlobalIndex)); 3820 } else { 3821 InitLinkScope<Emitter> ILS(this, InitLink::Decl(VD)); 3822 3823 if (VarT) { 3824 unsigned Offset = this->allocateLocalPrimitive( 3825 VD, *VarT, VD->getType().isConstQualified()); 3826 if (Init) { 3827 // If this is a toplevel declaration, create a scope for the 3828 // initializer. 3829 if (Toplevel) { 3830 LocalScope<Emitter> Scope(this); 3831 if (!this->visit(Init)) 3832 return false; 3833 return this->emitSetLocal(*VarT, Offset, VD) && Scope.destroyLocals(); 3834 } else { 3835 if (!this->visit(Init)) 3836 return false; 3837 return this->emitSetLocal(*VarT, Offset, VD); 3838 } 3839 } 3840 } else { 3841 if (std::optional<unsigned> Offset = this->allocateLocal(VD)) { 3842 if (!Init) 3843 return true; 3844 3845 if (!this->emitGetPtrLocal(*Offset, Init)) 3846 return false; 3847 3848 if (!visitInitializer(Init)) 3849 return false; 3850 3851 if (!this->emitFinishInit(Init)) 3852 return false; 3853 3854 return this->emitPopPtr(Init); 3855 } 3856 return false; 3857 } 3858 return true; 3859 } 3860 3861 return false; 3862 } 3863 3864 template <class Emitter> 3865 bool Compiler<Emitter>::visitAPValue(const APValue &Val, PrimType ValType, 3866 const Expr *E) { 3867 assert(!DiscardResult); 3868 if (Val.isInt()) 3869 return this->emitConst(Val.getInt(), ValType, E); 3870 else if (Val.isFloat()) 3871 return this->emitConstFloat(Val.getFloat(), E); 3872 3873 if (Val.isLValue()) { 3874 if (Val.isNullPointer()) 3875 return this->emitNull(ValType, nullptr, E); 3876 APValue::LValueBase Base = Val.getLValueBase(); 3877 if (const Expr *BaseExpr = Base.dyn_cast<const Expr *>()) 3878 return this->visit(BaseExpr); 3879 else if (const auto *VD = Base.dyn_cast<const ValueDecl *>()) { 3880 return this->visitDeclRef(VD, E); 3881 } 3882 } else if (Val.isMemberPointer()) { 3883 if (const ValueDecl *MemberDecl = Val.getMemberPointerDecl()) 3884 return this->emitGetMemberPtr(MemberDecl, E); 3885 return this->emitNullMemberPtr(nullptr, E); 3886 } 3887 3888 return false; 3889 } 3890 3891 template <class Emitter> 3892 bool Compiler<Emitter>::visitAPValueInitializer(const APValue &Val, 3893 const Expr *E) { 3894 3895 if (Val.isStruct()) { 3896 const Record *R = this->getRecord(E->getType()); 3897 assert(R); 3898 for (unsigned I = 0, N = Val.getStructNumFields(); I != N; ++I) { 3899 const APValue &F = Val.getStructField(I); 3900 const Record::Field *RF = R->getField(I); 3901 3902 if (F.isInt() || F.isFloat() || F.isLValue() || F.isMemberPointer()) { 3903 PrimType T = classifyPrim(RF->Decl->getType()); 3904 if (!this->visitAPValue(F, T, E)) 3905 return false; 3906 if (!this->emitInitField(T, RF->Offset, E)) 3907 return false; 3908 } else if (F.isArray()) { 3909 assert(RF->Desc->isPrimitiveArray()); 3910 const auto *ArrType = RF->Decl->getType()->getAsArrayTypeUnsafe(); 3911 PrimType ElemT = classifyPrim(ArrType->getElementType()); 3912 assert(ArrType); 3913 3914 if (!this->emitGetPtrField(RF->Offset, E)) 3915 return false; 3916 3917 for (unsigned A = 0, AN = F.getArraySize(); A != AN; ++A) { 3918 if (!this->visitAPValue(F.getArrayInitializedElt(A), ElemT, E)) 3919 return false; 3920 if (!this->emitInitElem(ElemT, A, E)) 3921 return false; 3922 } 3923 3924 if (!this->emitPopPtr(E)) 3925 return false; 3926 } else if (F.isStruct() || F.isUnion()) { 3927 if (!this->emitGetPtrField(RF->Offset, E)) 3928 return false; 3929 if (!this->visitAPValueInitializer(F, E)) 3930 return false; 3931 if (!this->emitPopPtr(E)) 3932 return false; 3933 } else { 3934 assert(false && "I don't think this should be possible"); 3935 } 3936 } 3937 return true; 3938 } else if (Val.isUnion()) { 3939 const FieldDecl *UnionField = Val.getUnionField(); 3940 const Record *R = this->getRecord(UnionField->getParent()); 3941 assert(R); 3942 const APValue &F = Val.getUnionValue(); 3943 const Record::Field *RF = R->getField(UnionField); 3944 PrimType T = classifyPrim(RF->Decl->getType()); 3945 if (!this->visitAPValue(F, T, E)) 3946 return false; 3947 return this->emitInitField(T, RF->Offset, E); 3948 } 3949 // TODO: Other types. 3950 3951 return false; 3952 } 3953 3954 template <class Emitter> 3955 bool Compiler<Emitter>::VisitBuiltinCallExpr(const CallExpr *E) { 3956 const Function *Func = getFunction(E->getDirectCallee()); 3957 if (!Func) 3958 return false; 3959 3960 // For these, we're expected to ultimately return an APValue pointing 3961 // to the CallExpr. This is needed to get the correct codegen. 3962 unsigned Builtin = E->getBuiltinCallee(); 3963 if (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 3964 Builtin == Builtin::BI__builtin___NSStringMakeConstantString || 3965 Builtin == Builtin::BI__builtin_ptrauth_sign_constant || 3966 Builtin == Builtin::BI__builtin_function_start) { 3967 if (std::optional<unsigned> GlobalOffset = P.createGlobal(E)) { 3968 if (!this->emitGetPtrGlobal(*GlobalOffset, E)) 3969 return false; 3970 3971 if (PrimType PT = classifyPrim(E); PT != PT_Ptr && isPtrType(PT)) 3972 return this->emitDecayPtr(PT_Ptr, PT, E); 3973 return true; 3974 } 3975 return false; 3976 } 3977 3978 QualType ReturnType = E->getType(); 3979 std::optional<PrimType> ReturnT = classify(E); 3980 3981 // Non-primitive return type. Prepare storage. 3982 if (!Initializing && !ReturnT && !ReturnType->isVoidType()) { 3983 std::optional<unsigned> LocalIndex = allocateLocal(E); 3984 if (!LocalIndex) 3985 return false; 3986 if (!this->emitGetPtrLocal(*LocalIndex, E)) 3987 return false; 3988 } 3989 3990 if (!Func->isUnevaluatedBuiltin()) { 3991 // Put arguments on the stack. 3992 for (const auto *Arg : E->arguments()) { 3993 if (!this->visit(Arg)) 3994 return false; 3995 } 3996 } 3997 3998 if (!this->emitCallBI(Func, E, E)) 3999 return false; 4000 4001 if (DiscardResult && !ReturnType->isVoidType()) { 4002 assert(ReturnT); 4003 return this->emitPop(*ReturnT, E); 4004 } 4005 4006 return true; 4007 } 4008 4009 template <class Emitter> 4010 bool Compiler<Emitter>::VisitCallExpr(const CallExpr *E) { 4011 if (E->getBuiltinCallee()) 4012 return VisitBuiltinCallExpr(E); 4013 4014 QualType ReturnType = E->getCallReturnType(Ctx.getASTContext()); 4015 std::optional<PrimType> T = classify(ReturnType); 4016 bool HasRVO = !ReturnType->isVoidType() && !T; 4017 const FunctionDecl *FuncDecl = E->getDirectCallee(); 4018 4019 if (HasRVO) { 4020 if (DiscardResult) { 4021 // If we need to discard the return value but the function returns its 4022 // value via an RVO pointer, we need to create one such pointer just 4023 // for this call. 4024 if (std::optional<unsigned> LocalIndex = allocateLocal(E)) { 4025 if (!this->emitGetPtrLocal(*LocalIndex, E)) 4026 return false; 4027 } 4028 } else { 4029 // We need the result. Prepare a pointer to return or 4030 // dup the current one. 4031 if (!Initializing) { 4032 if (std::optional<unsigned> LocalIndex = allocateLocal(E)) { 4033 if (!this->emitGetPtrLocal(*LocalIndex, E)) 4034 return false; 4035 } 4036 } 4037 if (!this->emitDupPtr(E)) 4038 return false; 4039 } 4040 } 4041 4042 SmallVector<const Expr *, 8> Args( 4043 llvm::ArrayRef(E->getArgs(), E->getNumArgs())); 4044 4045 bool IsAssignmentOperatorCall = false; 4046 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 4047 OCE && OCE->isAssignmentOp()) { 4048 // Just like with regular assignments, we need to special-case assignment 4049 // operators here and evaluate the RHS (the second arg) before the LHS (the 4050 // first arg. We fix this by using a Flip op later. 4051 assert(Args.size() == 2); 4052 IsAssignmentOperatorCall = true; 4053 std::reverse(Args.begin(), Args.end()); 4054 } 4055 // Calling a static operator will still 4056 // pass the instance, but we don't need it. 4057 // Discard it here. 4058 if (isa<CXXOperatorCallExpr>(E)) { 4059 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl); 4060 MD && MD->isStatic()) { 4061 if (!this->discard(E->getArg(0))) 4062 return false; 4063 // Drop first arg. 4064 Args.erase(Args.begin()); 4065 } 4066 } 4067 4068 std::optional<unsigned> CalleeOffset; 4069 // Add the (optional, implicit) This pointer. 4070 if (const auto *MC = dyn_cast<CXXMemberCallExpr>(E)) { 4071 if (!FuncDecl && classifyPrim(E->getCallee()) == PT_MemberPtr) { 4072 // If we end up creating a CallPtr op for this, we need the base of the 4073 // member pointer as the instance pointer, and later extract the function 4074 // decl as the function pointer. 4075 const Expr *Callee = E->getCallee(); 4076 CalleeOffset = 4077 this->allocateLocalPrimitive(Callee, PT_MemberPtr, true, false); 4078 if (!this->visit(Callee)) 4079 return false; 4080 if (!this->emitSetLocal(PT_MemberPtr, *CalleeOffset, E)) 4081 return false; 4082 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E)) 4083 return false; 4084 if (!this->emitGetMemberPtrBase(E)) 4085 return false; 4086 } else if (!this->visit(MC->getImplicitObjectArgument())) { 4087 return false; 4088 } 4089 } else if (!FuncDecl) { 4090 const Expr *Callee = E->getCallee(); 4091 CalleeOffset = this->allocateLocalPrimitive(Callee, PT_FnPtr, true, false); 4092 if (!this->visit(Callee)) 4093 return false; 4094 if (!this->emitSetLocal(PT_FnPtr, *CalleeOffset, E)) 4095 return false; 4096 } 4097 4098 llvm::BitVector NonNullArgs = collectNonNullArgs(FuncDecl, Args); 4099 // Put arguments on the stack. 4100 unsigned ArgIndex = 0; 4101 for (const auto *Arg : Args) { 4102 if (!this->visit(Arg)) 4103 return false; 4104 4105 // If we know the callee already, check the known parametrs for nullability. 4106 if (FuncDecl && NonNullArgs[ArgIndex]) { 4107 PrimType ArgT = classify(Arg).value_or(PT_Ptr); 4108 if (ArgT == PT_Ptr || ArgT == PT_FnPtr) { 4109 if (!this->emitCheckNonNullArg(ArgT, Arg)) 4110 return false; 4111 } 4112 } 4113 ++ArgIndex; 4114 } 4115 4116 // Undo the argument reversal we did earlier. 4117 if (IsAssignmentOperatorCall) { 4118 assert(Args.size() == 2); 4119 PrimType Arg1T = classify(Args[0]).value_or(PT_Ptr); 4120 PrimType Arg2T = classify(Args[1]).value_or(PT_Ptr); 4121 if (!this->emitFlip(Arg2T, Arg1T, E)) 4122 return false; 4123 } 4124 4125 if (FuncDecl) { 4126 const Function *Func = getFunction(FuncDecl); 4127 if (!Func) 4128 return false; 4129 assert(HasRVO == Func->hasRVO()); 4130 4131 bool HasQualifier = false; 4132 if (const auto *ME = dyn_cast<MemberExpr>(E->getCallee())) 4133 HasQualifier = ME->hasQualifier(); 4134 4135 bool IsVirtual = false; 4136 if (const auto *MD = dyn_cast<CXXMethodDecl>(FuncDecl)) 4137 IsVirtual = MD->isVirtual(); 4138 4139 // In any case call the function. The return value will end up on the stack 4140 // and if the function has RVO, we already have the pointer on the stack to 4141 // write the result into. 4142 if (IsVirtual && !HasQualifier) { 4143 uint32_t VarArgSize = 0; 4144 unsigned NumParams = 4145 Func->getNumWrittenParams() + isa<CXXOperatorCallExpr>(E); 4146 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I) 4147 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr))); 4148 4149 if (!this->emitCallVirt(Func, VarArgSize, E)) 4150 return false; 4151 } else if (Func->isVariadic()) { 4152 uint32_t VarArgSize = 0; 4153 unsigned NumParams = 4154 Func->getNumWrittenParams() + isa<CXXOperatorCallExpr>(E); 4155 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I) 4156 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr))); 4157 if (!this->emitCallVar(Func, VarArgSize, E)) 4158 return false; 4159 } else { 4160 if (!this->emitCall(Func, 0, E)) 4161 return false; 4162 } 4163 } else { 4164 // Indirect call. Visit the callee, which will leave a FunctionPointer on 4165 // the stack. Cleanup of the returned value if necessary will be done after 4166 // the function call completed. 4167 4168 // Sum the size of all args from the call expr. 4169 uint32_t ArgSize = 0; 4170 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) 4171 ArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr))); 4172 4173 // Get the callee, either from a member pointer or function pointer saved in 4174 // CalleeOffset. 4175 if (isa<CXXMemberCallExpr>(E) && CalleeOffset) { 4176 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E)) 4177 return false; 4178 if (!this->emitGetMemberPtrDecl(E)) 4179 return false; 4180 } else { 4181 if (!this->emitGetLocal(PT_FnPtr, *CalleeOffset, E)) 4182 return false; 4183 } 4184 if (!this->emitCallPtr(ArgSize, E, E)) 4185 return false; 4186 } 4187 4188 // Cleanup for discarded return values. 4189 if (DiscardResult && !ReturnType->isVoidType() && T) 4190 return this->emitPop(*T, E); 4191 4192 return true; 4193 } 4194 4195 template <class Emitter> 4196 bool Compiler<Emitter>::VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 4197 SourceLocScope<Emitter> SLS(this, E); 4198 4199 return this->delegate(E->getExpr()); 4200 } 4201 4202 template <class Emitter> 4203 bool Compiler<Emitter>::VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 4204 SourceLocScope<Emitter> SLS(this, E); 4205 4206 const Expr *SubExpr = E->getExpr(); 4207 if (std::optional<PrimType> T = classify(E->getExpr())) 4208 return this->visit(SubExpr); 4209 4210 assert(Initializing); 4211 return this->visitInitializer(SubExpr); 4212 } 4213 4214 template <class Emitter> 4215 bool Compiler<Emitter>::VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 4216 if (DiscardResult) 4217 return true; 4218 4219 return this->emitConstBool(E->getValue(), E); 4220 } 4221 4222 template <class Emitter> 4223 bool Compiler<Emitter>::VisitCXXNullPtrLiteralExpr( 4224 const CXXNullPtrLiteralExpr *E) { 4225 if (DiscardResult) 4226 return true; 4227 4228 return this->emitNullPtr(nullptr, E); 4229 } 4230 4231 template <class Emitter> 4232 bool Compiler<Emitter>::VisitGNUNullExpr(const GNUNullExpr *E) { 4233 if (DiscardResult) 4234 return true; 4235 4236 assert(E->getType()->isIntegerType()); 4237 4238 PrimType T = classifyPrim(E->getType()); 4239 return this->emitZero(T, E); 4240 } 4241 4242 template <class Emitter> 4243 bool Compiler<Emitter>::VisitCXXThisExpr(const CXXThisExpr *E) { 4244 if (DiscardResult) 4245 return true; 4246 4247 if (this->LambdaThisCapture.Offset > 0) { 4248 if (this->LambdaThisCapture.IsPtr) 4249 return this->emitGetThisFieldPtr(this->LambdaThisCapture.Offset, E); 4250 return this->emitGetPtrThisField(this->LambdaThisCapture.Offset, E); 4251 } 4252 4253 // In some circumstances, the 'this' pointer does not actually refer to the 4254 // instance pointer of the current function frame, but e.g. to the declaration 4255 // currently being initialized. Here we emit the necessary instruction(s) for 4256 // this scenario. 4257 if (!InitStackActive || !E->isImplicit()) 4258 return this->emitThis(E); 4259 4260 if (InitStackActive && !InitStack.empty()) { 4261 unsigned StartIndex = 0; 4262 for (StartIndex = InitStack.size() - 1; StartIndex > 0; --StartIndex) { 4263 if (InitStack[StartIndex].Kind != InitLink::K_Field && 4264 InitStack[StartIndex].Kind != InitLink::K_Elem) 4265 break; 4266 } 4267 4268 for (unsigned I = StartIndex, N = InitStack.size(); I != N; ++I) { 4269 if (!InitStack[I].template emit<Emitter>(this, E)) 4270 return false; 4271 } 4272 return true; 4273 } 4274 return this->emitThis(E); 4275 } 4276 4277 template <class Emitter> bool Compiler<Emitter>::visitStmt(const Stmt *S) { 4278 switch (S->getStmtClass()) { 4279 case Stmt::CompoundStmtClass: 4280 return visitCompoundStmt(cast<CompoundStmt>(S)); 4281 case Stmt::DeclStmtClass: 4282 return visitDeclStmt(cast<DeclStmt>(S)); 4283 case Stmt::ReturnStmtClass: 4284 return visitReturnStmt(cast<ReturnStmt>(S)); 4285 case Stmt::IfStmtClass: 4286 return visitIfStmt(cast<IfStmt>(S)); 4287 case Stmt::WhileStmtClass: 4288 return visitWhileStmt(cast<WhileStmt>(S)); 4289 case Stmt::DoStmtClass: 4290 return visitDoStmt(cast<DoStmt>(S)); 4291 case Stmt::ForStmtClass: 4292 return visitForStmt(cast<ForStmt>(S)); 4293 case Stmt::CXXForRangeStmtClass: 4294 return visitCXXForRangeStmt(cast<CXXForRangeStmt>(S)); 4295 case Stmt::BreakStmtClass: 4296 return visitBreakStmt(cast<BreakStmt>(S)); 4297 case Stmt::ContinueStmtClass: 4298 return visitContinueStmt(cast<ContinueStmt>(S)); 4299 case Stmt::SwitchStmtClass: 4300 return visitSwitchStmt(cast<SwitchStmt>(S)); 4301 case Stmt::CaseStmtClass: 4302 return visitCaseStmt(cast<CaseStmt>(S)); 4303 case Stmt::DefaultStmtClass: 4304 return visitDefaultStmt(cast<DefaultStmt>(S)); 4305 case Stmt::AttributedStmtClass: 4306 return visitAttributedStmt(cast<AttributedStmt>(S)); 4307 case Stmt::CXXTryStmtClass: 4308 return visitCXXTryStmt(cast<CXXTryStmt>(S)); 4309 case Stmt::NullStmtClass: 4310 return true; 4311 // Always invalid statements. 4312 case Stmt::GCCAsmStmtClass: 4313 case Stmt::MSAsmStmtClass: 4314 case Stmt::GotoStmtClass: 4315 return this->emitInvalid(S); 4316 case Stmt::LabelStmtClass: 4317 return this->visitStmt(cast<LabelStmt>(S)->getSubStmt()); 4318 default: { 4319 if (const auto *E = dyn_cast<Expr>(S)) 4320 return this->discard(E); 4321 return false; 4322 } 4323 } 4324 } 4325 4326 template <class Emitter> 4327 bool Compiler<Emitter>::visitCompoundStmt(const CompoundStmt *S) { 4328 BlockScope<Emitter> Scope(this); 4329 for (const auto *InnerStmt : S->body()) 4330 if (!visitStmt(InnerStmt)) 4331 return false; 4332 return Scope.destroyLocals(); 4333 } 4334 4335 template <class Emitter> 4336 bool Compiler<Emitter>::visitDeclStmt(const DeclStmt *DS) { 4337 for (const auto *D : DS->decls()) { 4338 if (isa<StaticAssertDecl, TagDecl, TypedefNameDecl, UsingEnumDecl, 4339 FunctionDecl>(D)) 4340 continue; 4341 4342 const auto *VD = dyn_cast<VarDecl>(D); 4343 if (!VD) 4344 return false; 4345 if (!this->visitVarDecl(VD)) 4346 return false; 4347 } 4348 4349 return true; 4350 } 4351 4352 template <class Emitter> 4353 bool Compiler<Emitter>::visitReturnStmt(const ReturnStmt *RS) { 4354 if (this->InStmtExpr) 4355 return this->emitUnsupported(RS); 4356 4357 if (const Expr *RE = RS->getRetValue()) { 4358 LocalScope<Emitter> RetScope(this); 4359 if (ReturnType) { 4360 // Primitive types are simply returned. 4361 if (!this->visit(RE)) 4362 return false; 4363 this->emitCleanup(); 4364 return this->emitRet(*ReturnType, RS); 4365 } else if (RE->getType()->isVoidType()) { 4366 if (!this->visit(RE)) 4367 return false; 4368 } else { 4369 // RVO - construct the value in the return location. 4370 if (!this->emitRVOPtr(RE)) 4371 return false; 4372 if (!this->visitInitializer(RE)) 4373 return false; 4374 if (!this->emitPopPtr(RE)) 4375 return false; 4376 4377 this->emitCleanup(); 4378 return this->emitRetVoid(RS); 4379 } 4380 } 4381 4382 // Void return. 4383 this->emitCleanup(); 4384 return this->emitRetVoid(RS); 4385 } 4386 4387 template <class Emitter> bool Compiler<Emitter>::visitIfStmt(const IfStmt *IS) { 4388 if (auto *CondInit = IS->getInit()) 4389 if (!visitStmt(CondInit)) 4390 return false; 4391 4392 if (const DeclStmt *CondDecl = IS->getConditionVariableDeclStmt()) 4393 if (!visitDeclStmt(CondDecl)) 4394 return false; 4395 4396 // Compile condition. 4397 if (IS->isNonNegatedConsteval()) { 4398 if (!this->emitIsConstantContext(IS)) 4399 return false; 4400 } else if (IS->isNegatedConsteval()) { 4401 if (!this->emitIsConstantContext(IS)) 4402 return false; 4403 if (!this->emitInv(IS)) 4404 return false; 4405 } else { 4406 if (!this->visitBool(IS->getCond())) 4407 return false; 4408 } 4409 4410 if (const Stmt *Else = IS->getElse()) { 4411 LabelTy LabelElse = this->getLabel(); 4412 LabelTy LabelEnd = this->getLabel(); 4413 if (!this->jumpFalse(LabelElse)) 4414 return false; 4415 if (!visitStmt(IS->getThen())) 4416 return false; 4417 if (!this->jump(LabelEnd)) 4418 return false; 4419 this->emitLabel(LabelElse); 4420 if (!visitStmt(Else)) 4421 return false; 4422 this->emitLabel(LabelEnd); 4423 } else { 4424 LabelTy LabelEnd = this->getLabel(); 4425 if (!this->jumpFalse(LabelEnd)) 4426 return false; 4427 if (!visitStmt(IS->getThen())) 4428 return false; 4429 this->emitLabel(LabelEnd); 4430 } 4431 4432 return true; 4433 } 4434 4435 template <class Emitter> 4436 bool Compiler<Emitter>::visitWhileStmt(const WhileStmt *S) { 4437 const Expr *Cond = S->getCond(); 4438 const Stmt *Body = S->getBody(); 4439 4440 LabelTy CondLabel = this->getLabel(); // Label before the condition. 4441 LabelTy EndLabel = this->getLabel(); // Label after the loop. 4442 LoopScope<Emitter> LS(this, EndLabel, CondLabel); 4443 4444 this->fallthrough(CondLabel); 4445 this->emitLabel(CondLabel); 4446 4447 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) 4448 if (!visitDeclStmt(CondDecl)) 4449 return false; 4450 4451 if (!this->visitBool(Cond)) 4452 return false; 4453 if (!this->jumpFalse(EndLabel)) 4454 return false; 4455 4456 if (!this->visitStmt(Body)) 4457 return false; 4458 4459 if (!this->jump(CondLabel)) 4460 return false; 4461 this->fallthrough(EndLabel); 4462 this->emitLabel(EndLabel); 4463 4464 return true; 4465 } 4466 4467 template <class Emitter> bool Compiler<Emitter>::visitDoStmt(const DoStmt *S) { 4468 const Expr *Cond = S->getCond(); 4469 const Stmt *Body = S->getBody(); 4470 4471 LabelTy StartLabel = this->getLabel(); 4472 LabelTy EndLabel = this->getLabel(); 4473 LabelTy CondLabel = this->getLabel(); 4474 LoopScope<Emitter> LS(this, EndLabel, CondLabel); 4475 4476 this->fallthrough(StartLabel); 4477 this->emitLabel(StartLabel); 4478 { 4479 if (!this->visitStmt(Body)) 4480 return false; 4481 this->fallthrough(CondLabel); 4482 this->emitLabel(CondLabel); 4483 if (!this->visitBool(Cond)) 4484 return false; 4485 } 4486 if (!this->jumpTrue(StartLabel)) 4487 return false; 4488 4489 this->fallthrough(EndLabel); 4490 this->emitLabel(EndLabel); 4491 return true; 4492 } 4493 4494 template <class Emitter> 4495 bool Compiler<Emitter>::visitForStmt(const ForStmt *S) { 4496 // for (Init; Cond; Inc) { Body } 4497 const Stmt *Init = S->getInit(); 4498 const Expr *Cond = S->getCond(); 4499 const Expr *Inc = S->getInc(); 4500 const Stmt *Body = S->getBody(); 4501 4502 LabelTy EndLabel = this->getLabel(); 4503 LabelTy CondLabel = this->getLabel(); 4504 LabelTy IncLabel = this->getLabel(); 4505 LoopScope<Emitter> LS(this, EndLabel, IncLabel); 4506 4507 if (Init && !this->visitStmt(Init)) 4508 return false; 4509 4510 this->fallthrough(CondLabel); 4511 this->emitLabel(CondLabel); 4512 4513 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) 4514 if (!visitDeclStmt(CondDecl)) 4515 return false; 4516 4517 if (Cond) { 4518 if (!this->visitBool(Cond)) 4519 return false; 4520 if (!this->jumpFalse(EndLabel)) 4521 return false; 4522 } 4523 4524 { 4525 if (Body && !this->visitStmt(Body)) 4526 return false; 4527 4528 this->fallthrough(IncLabel); 4529 this->emitLabel(IncLabel); 4530 if (Inc && !this->discard(Inc)) 4531 return false; 4532 } 4533 4534 if (!this->jump(CondLabel)) 4535 return false; 4536 this->fallthrough(EndLabel); 4537 this->emitLabel(EndLabel); 4538 return true; 4539 } 4540 4541 template <class Emitter> 4542 bool Compiler<Emitter>::visitCXXForRangeStmt(const CXXForRangeStmt *S) { 4543 const Stmt *Init = S->getInit(); 4544 const Expr *Cond = S->getCond(); 4545 const Expr *Inc = S->getInc(); 4546 const Stmt *Body = S->getBody(); 4547 const Stmt *BeginStmt = S->getBeginStmt(); 4548 const Stmt *RangeStmt = S->getRangeStmt(); 4549 const Stmt *EndStmt = S->getEndStmt(); 4550 const VarDecl *LoopVar = S->getLoopVariable(); 4551 4552 LabelTy EndLabel = this->getLabel(); 4553 LabelTy CondLabel = this->getLabel(); 4554 LabelTy IncLabel = this->getLabel(); 4555 LoopScope<Emitter> LS(this, EndLabel, IncLabel); 4556 4557 // Emit declarations needed in the loop. 4558 if (Init && !this->visitStmt(Init)) 4559 return false; 4560 if (!this->visitStmt(RangeStmt)) 4561 return false; 4562 if (!this->visitStmt(BeginStmt)) 4563 return false; 4564 if (!this->visitStmt(EndStmt)) 4565 return false; 4566 4567 // Now the condition as well as the loop variable assignment. 4568 this->fallthrough(CondLabel); 4569 this->emitLabel(CondLabel); 4570 if (!this->visitBool(Cond)) 4571 return false; 4572 if (!this->jumpFalse(EndLabel)) 4573 return false; 4574 4575 if (!this->visitVarDecl(LoopVar)) 4576 return false; 4577 4578 // Body. 4579 { 4580 if (!this->visitStmt(Body)) 4581 return false; 4582 4583 this->fallthrough(IncLabel); 4584 this->emitLabel(IncLabel); 4585 if (!this->discard(Inc)) 4586 return false; 4587 } 4588 4589 if (!this->jump(CondLabel)) 4590 return false; 4591 4592 this->fallthrough(EndLabel); 4593 this->emitLabel(EndLabel); 4594 return true; 4595 } 4596 4597 template <class Emitter> 4598 bool Compiler<Emitter>::visitBreakStmt(const BreakStmt *S) { 4599 if (!BreakLabel) 4600 return false; 4601 4602 this->emitCleanup(); 4603 return this->jump(*BreakLabel); 4604 } 4605 4606 template <class Emitter> 4607 bool Compiler<Emitter>::visitContinueStmt(const ContinueStmt *S) { 4608 if (!ContinueLabel) 4609 return false; 4610 4611 this->emitCleanup(); 4612 return this->jump(*ContinueLabel); 4613 } 4614 4615 template <class Emitter> 4616 bool Compiler<Emitter>::visitSwitchStmt(const SwitchStmt *S) { 4617 const Expr *Cond = S->getCond(); 4618 PrimType CondT = this->classifyPrim(Cond->getType()); 4619 4620 LabelTy EndLabel = this->getLabel(); 4621 OptLabelTy DefaultLabel = std::nullopt; 4622 unsigned CondVar = this->allocateLocalPrimitive(Cond, CondT, true, false); 4623 4624 if (const auto *CondInit = S->getInit()) 4625 if (!visitStmt(CondInit)) 4626 return false; 4627 4628 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) 4629 if (!visitDeclStmt(CondDecl)) 4630 return false; 4631 4632 // Initialize condition variable. 4633 if (!this->visit(Cond)) 4634 return false; 4635 if (!this->emitSetLocal(CondT, CondVar, S)) 4636 return false; 4637 4638 CaseMap CaseLabels; 4639 // Create labels and comparison ops for all case statements. 4640 for (const SwitchCase *SC = S->getSwitchCaseList(); SC; 4641 SC = SC->getNextSwitchCase()) { 4642 if (const auto *CS = dyn_cast<CaseStmt>(SC)) { 4643 // FIXME: Implement ranges. 4644 if (CS->caseStmtIsGNURange()) 4645 return false; 4646 CaseLabels[SC] = this->getLabel(); 4647 4648 const Expr *Value = CS->getLHS(); 4649 PrimType ValueT = this->classifyPrim(Value->getType()); 4650 4651 // Compare the case statement's value to the switch condition. 4652 if (!this->emitGetLocal(CondT, CondVar, CS)) 4653 return false; 4654 if (!this->visit(Value)) 4655 return false; 4656 4657 // Compare and jump to the case label. 4658 if (!this->emitEQ(ValueT, S)) 4659 return false; 4660 if (!this->jumpTrue(CaseLabels[CS])) 4661 return false; 4662 } else { 4663 assert(!DefaultLabel); 4664 DefaultLabel = this->getLabel(); 4665 } 4666 } 4667 4668 // If none of the conditions above were true, fall through to the default 4669 // statement or jump after the switch statement. 4670 if (DefaultLabel) { 4671 if (!this->jump(*DefaultLabel)) 4672 return false; 4673 } else { 4674 if (!this->jump(EndLabel)) 4675 return false; 4676 } 4677 4678 SwitchScope<Emitter> SS(this, std::move(CaseLabels), EndLabel, DefaultLabel); 4679 if (!this->visitStmt(S->getBody())) 4680 return false; 4681 this->emitLabel(EndLabel); 4682 return true; 4683 } 4684 4685 template <class Emitter> 4686 bool Compiler<Emitter>::visitCaseStmt(const CaseStmt *S) { 4687 this->emitLabel(CaseLabels[S]); 4688 return this->visitStmt(S->getSubStmt()); 4689 } 4690 4691 template <class Emitter> 4692 bool Compiler<Emitter>::visitDefaultStmt(const DefaultStmt *S) { 4693 this->emitLabel(*DefaultLabel); 4694 return this->visitStmt(S->getSubStmt()); 4695 } 4696 4697 template <class Emitter> 4698 bool Compiler<Emitter>::visitAttributedStmt(const AttributedStmt *S) { 4699 if (this->Ctx.getLangOpts().CXXAssumptions && 4700 !this->Ctx.getLangOpts().MSVCCompat) { 4701 for (const Attr *A : S->getAttrs()) { 4702 auto *AA = dyn_cast<CXXAssumeAttr>(A); 4703 if (!AA) 4704 continue; 4705 4706 assert(isa<NullStmt>(S->getSubStmt())); 4707 4708 const Expr *Assumption = AA->getAssumption(); 4709 if (Assumption->isValueDependent()) 4710 return false; 4711 4712 if (Assumption->HasSideEffects(this->Ctx.getASTContext())) 4713 continue; 4714 4715 // Evaluate assumption. 4716 if (!this->visitBool(Assumption)) 4717 return false; 4718 4719 if (!this->emitAssume(Assumption)) 4720 return false; 4721 } 4722 } 4723 4724 // Ignore other attributes. 4725 return this->visitStmt(S->getSubStmt()); 4726 } 4727 4728 template <class Emitter> 4729 bool Compiler<Emitter>::visitCXXTryStmt(const CXXTryStmt *S) { 4730 // Ignore all handlers. 4731 return this->visitStmt(S->getTryBlock()); 4732 } 4733 4734 template <class Emitter> 4735 bool Compiler<Emitter>::emitLambdaStaticInvokerBody(const CXXMethodDecl *MD) { 4736 assert(MD->isLambdaStaticInvoker()); 4737 assert(MD->hasBody()); 4738 assert(cast<CompoundStmt>(MD->getBody())->body_empty()); 4739 4740 const CXXRecordDecl *ClosureClass = MD->getParent(); 4741 const CXXMethodDecl *LambdaCallOp = ClosureClass->getLambdaCallOperator(); 4742 assert(ClosureClass->captures_begin() == ClosureClass->captures_end()); 4743 const Function *Func = this->getFunction(LambdaCallOp); 4744 if (!Func) 4745 return false; 4746 assert(Func->hasThisPointer()); 4747 assert(Func->getNumParams() == (MD->getNumParams() + 1 + Func->hasRVO())); 4748 4749 if (Func->hasRVO()) { 4750 if (!this->emitRVOPtr(MD)) 4751 return false; 4752 } 4753 4754 // The lambda call operator needs an instance pointer, but we don't have 4755 // one here, and we don't need one either because the lambda cannot have 4756 // any captures, as verified above. Emit a null pointer. This is then 4757 // special-cased when interpreting to not emit any misleading diagnostics. 4758 if (!this->emitNullPtr(nullptr, MD)) 4759 return false; 4760 4761 // Forward all arguments from the static invoker to the lambda call operator. 4762 for (const ParmVarDecl *PVD : MD->parameters()) { 4763 auto It = this->Params.find(PVD); 4764 assert(It != this->Params.end()); 4765 4766 // We do the lvalue-to-rvalue conversion manually here, so no need 4767 // to care about references. 4768 PrimType ParamType = this->classify(PVD->getType()).value_or(PT_Ptr); 4769 if (!this->emitGetParam(ParamType, It->second.Offset, MD)) 4770 return false; 4771 } 4772 4773 if (!this->emitCall(Func, 0, LambdaCallOp)) 4774 return false; 4775 4776 this->emitCleanup(); 4777 if (ReturnType) 4778 return this->emitRet(*ReturnType, MD); 4779 4780 // Nothing to do, since we emitted the RVO pointer above. 4781 return this->emitRetVoid(MD); 4782 } 4783 4784 template <class Emitter> 4785 bool Compiler<Emitter>::checkLiteralType(const Expr *E) { 4786 if (Ctx.getLangOpts().CPlusPlus23) 4787 return true; 4788 4789 if (!E->isPRValue() || E->getType()->isLiteralType(Ctx.getASTContext())) 4790 return true; 4791 4792 return this->emitCheckLiteralType(E->getType().getTypePtr(), E); 4793 } 4794 4795 template <class Emitter> 4796 bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) { 4797 assert(!ReturnType); 4798 4799 auto emitFieldInitializer = [&](const Record::Field *F, unsigned FieldOffset, 4800 const Expr *InitExpr) -> bool { 4801 // We don't know what to do with these, so just return false. 4802 if (InitExpr->getType().isNull()) 4803 return false; 4804 4805 if (std::optional<PrimType> T = this->classify(InitExpr)) { 4806 if (!this->visit(InitExpr)) 4807 return false; 4808 4809 if (F->isBitField()) 4810 return this->emitInitThisBitField(*T, F, FieldOffset, InitExpr); 4811 return this->emitInitThisField(*T, FieldOffset, InitExpr); 4812 } 4813 // Non-primitive case. Get a pointer to the field-to-initialize 4814 // on the stack and call visitInitialzer() for it. 4815 InitLinkScope<Emitter> FieldScope(this, InitLink::Field(F->Offset)); 4816 if (!this->emitGetPtrThisField(FieldOffset, InitExpr)) 4817 return false; 4818 4819 if (!this->visitInitializer(InitExpr)) 4820 return false; 4821 4822 return this->emitFinishInitPop(InitExpr); 4823 }; 4824 4825 const RecordDecl *RD = Ctor->getParent(); 4826 const Record *R = this->getRecord(RD); 4827 if (!R) 4828 return false; 4829 4830 if (R->isUnion() && Ctor->isCopyOrMoveConstructor()) { 4831 // union copy and move ctors are special. 4832 assert(cast<CompoundStmt>(Ctor->getBody())->body_empty()); 4833 if (!this->emitThis(Ctor)) 4834 return false; 4835 4836 auto PVD = Ctor->getParamDecl(0); 4837 ParamOffset PO = this->Params[PVD]; // Must exist. 4838 4839 if (!this->emitGetParam(PT_Ptr, PO.Offset, Ctor)) 4840 return false; 4841 4842 return this->emitMemcpy(Ctor) && this->emitPopPtr(Ctor) && 4843 this->emitRetVoid(Ctor); 4844 } 4845 4846 InitLinkScope<Emitter> InitScope(this, InitLink::This()); 4847 for (const auto *Init : Ctor->inits()) { 4848 // Scope needed for the initializers. 4849 BlockScope<Emitter> Scope(this); 4850 4851 const Expr *InitExpr = Init->getInit(); 4852 if (const FieldDecl *Member = Init->getMember()) { 4853 const Record::Field *F = R->getField(Member); 4854 4855 if (!emitFieldInitializer(F, F->Offset, InitExpr)) 4856 return false; 4857 } else if (const Type *Base = Init->getBaseClass()) { 4858 const auto *BaseDecl = Base->getAsCXXRecordDecl(); 4859 assert(BaseDecl); 4860 4861 if (Init->isBaseVirtual()) { 4862 assert(R->getVirtualBase(BaseDecl)); 4863 if (!this->emitGetPtrThisVirtBase(BaseDecl, InitExpr)) 4864 return false; 4865 4866 } else { 4867 // Base class initializer. 4868 // Get This Base and call initializer on it. 4869 const Record::Base *B = R->getBase(BaseDecl); 4870 assert(B); 4871 if (!this->emitGetPtrThisBase(B->Offset, InitExpr)) 4872 return false; 4873 } 4874 4875 if (!this->visitInitializer(InitExpr)) 4876 return false; 4877 if (!this->emitFinishInitPop(InitExpr)) 4878 return false; 4879 } else if (const IndirectFieldDecl *IFD = Init->getIndirectMember()) { 4880 assert(IFD->getChainingSize() >= 2); 4881 4882 unsigned NestedFieldOffset = 0; 4883 const Record::Field *NestedField = nullptr; 4884 for (const NamedDecl *ND : IFD->chain()) { 4885 const auto *FD = cast<FieldDecl>(ND); 4886 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent()); 4887 assert(FieldRecord); 4888 4889 NestedField = FieldRecord->getField(FD); 4890 assert(NestedField); 4891 4892 NestedFieldOffset += NestedField->Offset; 4893 } 4894 assert(NestedField); 4895 4896 if (!emitFieldInitializer(NestedField, NestedFieldOffset, InitExpr)) 4897 return false; 4898 } else { 4899 assert(Init->isDelegatingInitializer()); 4900 if (!this->emitThis(InitExpr)) 4901 return false; 4902 if (!this->visitInitializer(Init->getInit())) 4903 return false; 4904 if (!this->emitPopPtr(InitExpr)) 4905 return false; 4906 } 4907 4908 if (!Scope.destroyLocals()) 4909 return false; 4910 } 4911 4912 if (const auto *Body = Ctor->getBody()) 4913 if (!visitStmt(Body)) 4914 return false; 4915 4916 return this->emitRetVoid(SourceInfo{}); 4917 } 4918 4919 template <class Emitter> 4920 bool Compiler<Emitter>::compileDestructor(const CXXDestructorDecl *Dtor) { 4921 const RecordDecl *RD = Dtor->getParent(); 4922 const Record *R = this->getRecord(RD); 4923 if (!R) 4924 return false; 4925 4926 if (!Dtor->isTrivial() && Dtor->getBody()) { 4927 if (!this->visitStmt(Dtor->getBody())) 4928 return false; 4929 } 4930 4931 if (!this->emitThis(Dtor)) 4932 return false; 4933 4934 assert(R); 4935 if (!R->isUnion()) { 4936 // First, destroy all fields. 4937 for (const Record::Field &Field : llvm::reverse(R->fields())) { 4938 const Descriptor *D = Field.Desc; 4939 if (!D->isPrimitive() && !D->isPrimitiveArray()) { 4940 if (!this->emitGetPtrField(Field.Offset, SourceInfo{})) 4941 return false; 4942 if (!this->emitDestruction(D)) 4943 return false; 4944 if (!this->emitPopPtr(SourceInfo{})) 4945 return false; 4946 } 4947 } 4948 } 4949 4950 for (const Record::Base &Base : llvm::reverse(R->bases())) { 4951 if (!this->emitGetPtrBase(Base.Offset, SourceInfo{})) 4952 return false; 4953 if (!this->emitRecordDestruction(Base.R)) 4954 return false; 4955 if (!this->emitPopPtr(SourceInfo{})) 4956 return false; 4957 } 4958 4959 // FIXME: Virtual bases. 4960 return this->emitPopPtr(Dtor) && this->emitRetVoid(Dtor); 4961 } 4962 4963 template <class Emitter> 4964 bool Compiler<Emitter>::visitFunc(const FunctionDecl *F) { 4965 // Classify the return type. 4966 ReturnType = this->classify(F->getReturnType()); 4967 4968 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(F)) 4969 return this->compileConstructor(Ctor); 4970 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(F)) 4971 return this->compileDestructor(Dtor); 4972 4973 // Emit custom code if this is a lambda static invoker. 4974 if (const auto *MD = dyn_cast<CXXMethodDecl>(F); 4975 MD && MD->isLambdaStaticInvoker()) 4976 return this->emitLambdaStaticInvokerBody(MD); 4977 4978 // Regular functions. 4979 if (const auto *Body = F->getBody()) 4980 if (!visitStmt(Body)) 4981 return false; 4982 4983 // Emit a guard return to protect against a code path missing one. 4984 if (F->getReturnType()->isVoidType()) 4985 return this->emitRetVoid(SourceInfo{}); 4986 return this->emitNoRet(SourceInfo{}); 4987 } 4988 4989 template <class Emitter> 4990 bool Compiler<Emitter>::VisitUnaryOperator(const UnaryOperator *E) { 4991 const Expr *SubExpr = E->getSubExpr(); 4992 if (SubExpr->getType()->isAnyComplexType()) 4993 return this->VisitComplexUnaryOperator(E); 4994 if (SubExpr->getType()->isVectorType()) 4995 return this->VisitVectorUnaryOperator(E); 4996 std::optional<PrimType> T = classify(SubExpr->getType()); 4997 4998 switch (E->getOpcode()) { 4999 case UO_PostInc: { // x++ 5000 if (!Ctx.getLangOpts().CPlusPlus14) 5001 return this->emitInvalid(E); 5002 if (!T) 5003 return this->emitError(E); 5004 5005 if (!this->visit(SubExpr)) 5006 return false; 5007 5008 if (T == PT_Ptr || T == PT_FnPtr) { 5009 if (!this->emitIncPtr(E)) 5010 return false; 5011 5012 return DiscardResult ? this->emitPopPtr(E) : true; 5013 } 5014 5015 if (T == PT_Float) { 5016 return DiscardResult ? this->emitIncfPop(getRoundingMode(E), E) 5017 : this->emitIncf(getRoundingMode(E), E); 5018 } 5019 5020 return DiscardResult ? this->emitIncPop(*T, E) : this->emitInc(*T, E); 5021 } 5022 case UO_PostDec: { // x-- 5023 if (!Ctx.getLangOpts().CPlusPlus14) 5024 return this->emitInvalid(E); 5025 if (!T) 5026 return this->emitError(E); 5027 5028 if (!this->visit(SubExpr)) 5029 return false; 5030 5031 if (T == PT_Ptr || T == PT_FnPtr) { 5032 if (!this->emitDecPtr(E)) 5033 return false; 5034 5035 return DiscardResult ? this->emitPopPtr(E) : true; 5036 } 5037 5038 if (T == PT_Float) { 5039 return DiscardResult ? this->emitDecfPop(getRoundingMode(E), E) 5040 : this->emitDecf(getRoundingMode(E), E); 5041 } 5042 5043 return DiscardResult ? this->emitDecPop(*T, E) : this->emitDec(*T, E); 5044 } 5045 case UO_PreInc: { // ++x 5046 if (!Ctx.getLangOpts().CPlusPlus14) 5047 return this->emitInvalid(E); 5048 if (!T) 5049 return this->emitError(E); 5050 5051 if (!this->visit(SubExpr)) 5052 return false; 5053 5054 if (T == PT_Ptr || T == PT_FnPtr) { 5055 if (!this->emitLoadPtr(E)) 5056 return false; 5057 if (!this->emitConstUint8(1, E)) 5058 return false; 5059 if (!this->emitAddOffsetUint8(E)) 5060 return false; 5061 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E); 5062 } 5063 5064 // Post-inc and pre-inc are the same if the value is to be discarded. 5065 if (DiscardResult) { 5066 if (T == PT_Float) 5067 return this->emitIncfPop(getRoundingMode(E), E); 5068 return this->emitIncPop(*T, E); 5069 } 5070 5071 if (T == PT_Float) { 5072 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType()); 5073 if (!this->emitLoadFloat(E)) 5074 return false; 5075 if (!this->emitConstFloat(llvm::APFloat(TargetSemantics, 1), E)) 5076 return false; 5077 if (!this->emitAddf(getRoundingMode(E), E)) 5078 return false; 5079 if (!this->emitStoreFloat(E)) 5080 return false; 5081 } else { 5082 assert(isIntegralType(*T)); 5083 if (!this->emitLoad(*T, E)) 5084 return false; 5085 if (!this->emitConst(1, E)) 5086 return false; 5087 if (!this->emitAdd(*T, E)) 5088 return false; 5089 if (!this->emitStore(*T, E)) 5090 return false; 5091 } 5092 return E->isGLValue() || this->emitLoadPop(*T, E); 5093 } 5094 case UO_PreDec: { // --x 5095 if (!Ctx.getLangOpts().CPlusPlus14) 5096 return this->emitInvalid(E); 5097 if (!T) 5098 return this->emitError(E); 5099 5100 if (!this->visit(SubExpr)) 5101 return false; 5102 5103 if (T == PT_Ptr || T == PT_FnPtr) { 5104 if (!this->emitLoadPtr(E)) 5105 return false; 5106 if (!this->emitConstUint8(1, E)) 5107 return false; 5108 if (!this->emitSubOffsetUint8(E)) 5109 return false; 5110 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E); 5111 } 5112 5113 // Post-dec and pre-dec are the same if the value is to be discarded. 5114 if (DiscardResult) { 5115 if (T == PT_Float) 5116 return this->emitDecfPop(getRoundingMode(E), E); 5117 return this->emitDecPop(*T, E); 5118 } 5119 5120 if (T == PT_Float) { 5121 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType()); 5122 if (!this->emitLoadFloat(E)) 5123 return false; 5124 if (!this->emitConstFloat(llvm::APFloat(TargetSemantics, 1), E)) 5125 return false; 5126 if (!this->emitSubf(getRoundingMode(E), E)) 5127 return false; 5128 if (!this->emitStoreFloat(E)) 5129 return false; 5130 } else { 5131 assert(isIntegralType(*T)); 5132 if (!this->emitLoad(*T, E)) 5133 return false; 5134 if (!this->emitConst(1, E)) 5135 return false; 5136 if (!this->emitSub(*T, E)) 5137 return false; 5138 if (!this->emitStore(*T, E)) 5139 return false; 5140 } 5141 return E->isGLValue() || this->emitLoadPop(*T, E); 5142 } 5143 case UO_LNot: // !x 5144 if (!T) 5145 return this->emitError(E); 5146 5147 if (DiscardResult) 5148 return this->discard(SubExpr); 5149 5150 if (!this->visitBool(SubExpr)) 5151 return false; 5152 5153 if (!this->emitInv(E)) 5154 return false; 5155 5156 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool) 5157 return this->emitCast(PT_Bool, ET, E); 5158 return true; 5159 case UO_Minus: // -x 5160 if (!T) 5161 return this->emitError(E); 5162 5163 if (!this->visit(SubExpr)) 5164 return false; 5165 return DiscardResult ? this->emitPop(*T, E) : this->emitNeg(*T, E); 5166 case UO_Plus: // +x 5167 if (!T) 5168 return this->emitError(E); 5169 5170 if (!this->visit(SubExpr)) // noop 5171 return false; 5172 return DiscardResult ? this->emitPop(*T, E) : true; 5173 case UO_AddrOf: // &x 5174 if (E->getType()->isMemberPointerType()) { 5175 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 5176 // member can be formed. 5177 return this->emitGetMemberPtr(cast<DeclRefExpr>(SubExpr)->getDecl(), E); 5178 } 5179 // We should already have a pointer when we get here. 5180 return this->delegate(SubExpr); 5181 case UO_Deref: // *x 5182 if (DiscardResult) 5183 return this->discard(SubExpr); 5184 return this->visit(SubExpr); 5185 case UO_Not: // ~x 5186 if (!T) 5187 return this->emitError(E); 5188 5189 if (!this->visit(SubExpr)) 5190 return false; 5191 return DiscardResult ? this->emitPop(*T, E) : this->emitComp(*T, E); 5192 case UO_Real: // __real x 5193 assert(T); 5194 return this->delegate(SubExpr); 5195 case UO_Imag: { // __imag x 5196 assert(T); 5197 if (!this->discard(SubExpr)) 5198 return false; 5199 return this->visitZeroInitializer(*T, SubExpr->getType(), SubExpr); 5200 } 5201 case UO_Extension: 5202 return this->delegate(SubExpr); 5203 case UO_Coawait: 5204 assert(false && "Unhandled opcode"); 5205 } 5206 5207 return false; 5208 } 5209 5210 template <class Emitter> 5211 bool Compiler<Emitter>::VisitComplexUnaryOperator(const UnaryOperator *E) { 5212 const Expr *SubExpr = E->getSubExpr(); 5213 assert(SubExpr->getType()->isAnyComplexType()); 5214 5215 if (DiscardResult) 5216 return this->discard(SubExpr); 5217 5218 std::optional<PrimType> ResT = classify(E); 5219 auto prepareResult = [=]() -> bool { 5220 if (!ResT && !Initializing) { 5221 std::optional<unsigned> LocalIndex = allocateLocal(SubExpr); 5222 if (!LocalIndex) 5223 return false; 5224 return this->emitGetPtrLocal(*LocalIndex, E); 5225 } 5226 5227 return true; 5228 }; 5229 5230 // The offset of the temporary, if we created one. 5231 unsigned SubExprOffset = ~0u; 5232 auto createTemp = [=, &SubExprOffset]() -> bool { 5233 SubExprOffset = this->allocateLocalPrimitive(SubExpr, PT_Ptr, true, false); 5234 if (!this->visit(SubExpr)) 5235 return false; 5236 return this->emitSetLocal(PT_Ptr, SubExprOffset, E); 5237 }; 5238 5239 PrimType ElemT = classifyComplexElementType(SubExpr->getType()); 5240 auto getElem = [=](unsigned Offset, unsigned Index) -> bool { 5241 if (!this->emitGetLocal(PT_Ptr, Offset, E)) 5242 return false; 5243 return this->emitArrayElemPop(ElemT, Index, E); 5244 }; 5245 5246 switch (E->getOpcode()) { 5247 case UO_Minus: 5248 if (!prepareResult()) 5249 return false; 5250 if (!createTemp()) 5251 return false; 5252 for (unsigned I = 0; I != 2; ++I) { 5253 if (!getElem(SubExprOffset, I)) 5254 return false; 5255 if (!this->emitNeg(ElemT, E)) 5256 return false; 5257 if (!this->emitInitElem(ElemT, I, E)) 5258 return false; 5259 } 5260 break; 5261 5262 case UO_Plus: // +x 5263 case UO_AddrOf: // &x 5264 case UO_Deref: // *x 5265 return this->delegate(SubExpr); 5266 5267 case UO_LNot: 5268 if (!this->visit(SubExpr)) 5269 return false; 5270 if (!this->emitComplexBoolCast(SubExpr)) 5271 return false; 5272 if (!this->emitInv(E)) 5273 return false; 5274 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool) 5275 return this->emitCast(PT_Bool, ET, E); 5276 return true; 5277 5278 case UO_Real: 5279 return this->emitComplexReal(SubExpr); 5280 5281 case UO_Imag: 5282 if (!this->visit(SubExpr)) 5283 return false; 5284 5285 if (SubExpr->isLValue()) { 5286 if (!this->emitConstUint8(1, E)) 5287 return false; 5288 return this->emitArrayElemPtrPopUint8(E); 5289 } 5290 5291 // Since our _Complex implementation does not map to a primitive type, 5292 // we sometimes have to do the lvalue-to-rvalue conversion here manually. 5293 return this->emitArrayElemPop(classifyPrim(E->getType()), 1, E); 5294 5295 case UO_Not: // ~x 5296 if (!this->visit(SubExpr)) 5297 return false; 5298 // Negate the imaginary component. 5299 if (!this->emitArrayElem(ElemT, 1, E)) 5300 return false; 5301 if (!this->emitNeg(ElemT, E)) 5302 return false; 5303 if (!this->emitInitElem(ElemT, 1, E)) 5304 return false; 5305 return DiscardResult ? this->emitPopPtr(E) : true; 5306 5307 case UO_Extension: 5308 return this->delegate(SubExpr); 5309 5310 default: 5311 return this->emitInvalid(E); 5312 } 5313 5314 return true; 5315 } 5316 5317 template <class Emitter> 5318 bool Compiler<Emitter>::VisitVectorUnaryOperator(const UnaryOperator *E) { 5319 const Expr *SubExpr = E->getSubExpr(); 5320 assert(SubExpr->getType()->isVectorType()); 5321 5322 if (DiscardResult) 5323 return this->discard(SubExpr); 5324 5325 auto UnaryOp = E->getOpcode(); 5326 if (UnaryOp != UO_Plus && UnaryOp != UO_Minus && UnaryOp != UO_LNot && 5327 UnaryOp != UO_Not && UnaryOp != UO_AddrOf) 5328 return this->emitInvalid(E); 5329 5330 // Nothing to do here. 5331 if (UnaryOp == UO_Plus || UnaryOp == UO_AddrOf) 5332 return this->delegate(SubExpr); 5333 5334 if (!Initializing) { 5335 std::optional<unsigned> LocalIndex = allocateLocal(SubExpr); 5336 if (!LocalIndex) 5337 return false; 5338 if (!this->emitGetPtrLocal(*LocalIndex, E)) 5339 return false; 5340 } 5341 5342 // The offset of the temporary, if we created one. 5343 unsigned SubExprOffset = 5344 this->allocateLocalPrimitive(SubExpr, PT_Ptr, true, false); 5345 if (!this->visit(SubExpr)) 5346 return false; 5347 if (!this->emitSetLocal(PT_Ptr, SubExprOffset, E)) 5348 return false; 5349 5350 const auto *VecTy = SubExpr->getType()->getAs<VectorType>(); 5351 PrimType ElemT = classifyVectorElementType(SubExpr->getType()); 5352 auto getElem = [=](unsigned Offset, unsigned Index) -> bool { 5353 if (!this->emitGetLocal(PT_Ptr, Offset, E)) 5354 return false; 5355 return this->emitArrayElemPop(ElemT, Index, E); 5356 }; 5357 5358 switch (UnaryOp) { 5359 case UO_Minus: 5360 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) { 5361 if (!getElem(SubExprOffset, I)) 5362 return false; 5363 if (!this->emitNeg(ElemT, E)) 5364 return false; 5365 if (!this->emitInitElem(ElemT, I, E)) 5366 return false; 5367 } 5368 break; 5369 case UO_LNot: { // !x 5370 // In C++, the logic operators !, &&, || are available for vectors. !v is 5371 // equivalent to v == 0. 5372 // 5373 // The result of the comparison is a vector of the same width and number of 5374 // elements as the comparison operands with a signed integral element type. 5375 // 5376 // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html 5377 QualType ResultVecTy = E->getType(); 5378 PrimType ResultVecElemT = 5379 classifyPrim(ResultVecTy->getAs<VectorType>()->getElementType()); 5380 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) { 5381 if (!getElem(SubExprOffset, I)) 5382 return false; 5383 // operator ! on vectors returns -1 for 'truth', so negate it. 5384 if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E)) 5385 return false; 5386 if (!this->emitInv(E)) 5387 return false; 5388 if (!this->emitPrimCast(PT_Bool, ElemT, VecTy->getElementType(), E)) 5389 return false; 5390 if (!this->emitNeg(ElemT, E)) 5391 return false; 5392 if (ElemT != ResultVecElemT && 5393 !this->emitPrimCast(ElemT, ResultVecElemT, ResultVecTy, E)) 5394 return false; 5395 if (!this->emitInitElem(ResultVecElemT, I, E)) 5396 return false; 5397 } 5398 break; 5399 } 5400 case UO_Not: // ~x 5401 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) { 5402 if (!getElem(SubExprOffset, I)) 5403 return false; 5404 if (ElemT == PT_Bool) { 5405 if (!this->emitInv(E)) 5406 return false; 5407 } else { 5408 if (!this->emitComp(ElemT, E)) 5409 return false; 5410 } 5411 if (!this->emitInitElem(ElemT, I, E)) 5412 return false; 5413 } 5414 break; 5415 default: 5416 llvm_unreachable("Unsupported unary operators should be handled up front"); 5417 } 5418 return true; 5419 } 5420 5421 template <class Emitter> 5422 bool Compiler<Emitter>::visitDeclRef(const ValueDecl *D, const Expr *E) { 5423 if (DiscardResult) 5424 return true; 5425 5426 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) { 5427 return this->emitConst(ECD->getInitVal(), E); 5428 } else if (const auto *BD = dyn_cast<BindingDecl>(D)) { 5429 return this->visit(BD->getBinding()); 5430 } else if (const auto *FuncDecl = dyn_cast<FunctionDecl>(D)) { 5431 const Function *F = getFunction(FuncDecl); 5432 return F && this->emitGetFnPtr(F, E); 5433 } else if (const auto *TPOD = dyn_cast<TemplateParamObjectDecl>(D)) { 5434 if (std::optional<unsigned> Index = P.getOrCreateGlobal(D)) { 5435 if (!this->emitGetPtrGlobal(*Index, E)) 5436 return false; 5437 if (std::optional<PrimType> T = classify(E->getType())) { 5438 if (!this->visitAPValue(TPOD->getValue(), *T, E)) 5439 return false; 5440 return this->emitInitGlobal(*T, *Index, E); 5441 } 5442 return this->visitAPValueInitializer(TPOD->getValue(), E); 5443 } 5444 return false; 5445 } 5446 5447 // References are implemented via pointers, so when we see a DeclRefExpr 5448 // pointing to a reference, we need to get its value directly (i.e. the 5449 // pointer to the actual value) instead of a pointer to the pointer to the 5450 // value. 5451 bool IsReference = D->getType()->isReferenceType(); 5452 5453 // Check for local/global variables and parameters. 5454 if (auto It = Locals.find(D); It != Locals.end()) { 5455 const unsigned Offset = It->second.Offset; 5456 if (IsReference) 5457 return this->emitGetLocal(PT_Ptr, Offset, E); 5458 return this->emitGetPtrLocal(Offset, E); 5459 } else if (auto GlobalIndex = P.getGlobal(D)) { 5460 if (IsReference) { 5461 if (!Ctx.getLangOpts().CPlusPlus11) 5462 return this->emitGetGlobal(classifyPrim(E), *GlobalIndex, E); 5463 return this->emitGetGlobalUnchecked(classifyPrim(E), *GlobalIndex, E); 5464 } 5465 5466 return this->emitGetPtrGlobal(*GlobalIndex, E); 5467 } else if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) { 5468 if (auto It = this->Params.find(PVD); It != this->Params.end()) { 5469 if (IsReference || !It->second.IsPtr) 5470 return this->emitGetParam(classifyPrim(E), It->second.Offset, E); 5471 5472 return this->emitGetPtrParam(It->second.Offset, E); 5473 } 5474 } 5475 5476 // In case we need to re-visit a declaration. 5477 auto revisit = [&](const VarDecl *VD) -> bool { 5478 auto VarState = this->visitDecl(VD); 5479 5480 if (VarState.notCreated()) 5481 return true; 5482 if (!VarState) 5483 return false; 5484 // Retry. 5485 return this->visitDeclRef(D, E); 5486 }; 5487 5488 // Handle lambda captures. 5489 if (auto It = this->LambdaCaptures.find(D); 5490 It != this->LambdaCaptures.end()) { 5491 auto [Offset, IsPtr] = It->second; 5492 5493 if (IsPtr) 5494 return this->emitGetThisFieldPtr(Offset, E); 5495 return this->emitGetPtrThisField(Offset, E); 5496 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(E); 5497 DRE && DRE->refersToEnclosingVariableOrCapture()) { 5498 if (const auto *VD = dyn_cast<VarDecl>(D); VD && VD->isInitCapture()) 5499 return revisit(VD); 5500 } 5501 5502 if (D != InitializingDecl) { 5503 // Try to lazily visit (or emit dummy pointers for) declarations 5504 // we haven't seen yet. 5505 if (Ctx.getLangOpts().CPlusPlus) { 5506 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5507 const auto typeShouldBeVisited = [&](QualType T) -> bool { 5508 if (T.isConstant(Ctx.getASTContext())) 5509 return true; 5510 if (const auto *RT = T->getAs<ReferenceType>()) 5511 return RT->getPointeeType().isConstQualified(); 5512 return false; 5513 }; 5514 5515 // DecompositionDecls are just proxies for us. 5516 if (isa<DecompositionDecl>(VD)) 5517 return revisit(VD); 5518 5519 // Visit local const variables like normal. 5520 if ((VD->hasGlobalStorage() || VD->isLocalVarDecl() || 5521 VD->isStaticDataMember()) && 5522 typeShouldBeVisited(VD->getType())) 5523 return revisit(VD); 5524 } 5525 } else { 5526 if (const auto *VD = dyn_cast<VarDecl>(D); 5527 VD && VD->getAnyInitializer() && 5528 VD->getType().isConstant(Ctx.getASTContext()) && !VD->isWeak()) 5529 return revisit(VD); 5530 } 5531 } 5532 5533 if (std::optional<unsigned> I = P.getOrCreateDummy(D)) { 5534 if (!this->emitGetPtrGlobal(*I, E)) 5535 return false; 5536 if (E->getType()->isVoidType()) 5537 return true; 5538 // Convert the dummy pointer to another pointer type if we have to. 5539 if (PrimType PT = classifyPrim(E); PT != PT_Ptr) { 5540 if (isPtrType(PT)) 5541 return this->emitDecayPtr(PT_Ptr, PT, E); 5542 return false; 5543 } 5544 return true; 5545 } 5546 5547 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 5548 return this->emitInvalidDeclRef(DRE, E); 5549 return false; 5550 } 5551 5552 template <class Emitter> 5553 bool Compiler<Emitter>::VisitDeclRefExpr(const DeclRefExpr *E) { 5554 const auto *D = E->getDecl(); 5555 return this->visitDeclRef(D, E); 5556 } 5557 5558 template <class Emitter> void Compiler<Emitter>::emitCleanup() { 5559 for (VariableScope<Emitter> *C = VarScope; C; C = C->getParent()) 5560 C->emitDestruction(); 5561 } 5562 5563 template <class Emitter> 5564 unsigned Compiler<Emitter>::collectBaseOffset(const QualType BaseType, 5565 const QualType DerivedType) { 5566 const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * { 5567 if (const auto *R = Ty->getPointeeCXXRecordDecl()) 5568 return R; 5569 return Ty->getAsCXXRecordDecl(); 5570 }; 5571 const CXXRecordDecl *BaseDecl = extractRecordDecl(BaseType); 5572 const CXXRecordDecl *DerivedDecl = extractRecordDecl(DerivedType); 5573 5574 return Ctx.collectBaseOffset(BaseDecl, DerivedDecl); 5575 } 5576 5577 /// Emit casts from a PrimType to another PrimType. 5578 template <class Emitter> 5579 bool Compiler<Emitter>::emitPrimCast(PrimType FromT, PrimType ToT, 5580 QualType ToQT, const Expr *E) { 5581 5582 if (FromT == PT_Float) { 5583 // Floating to floating. 5584 if (ToT == PT_Float) { 5585 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT); 5586 return this->emitCastFP(ToSem, getRoundingMode(E), E); 5587 } 5588 5589 if (ToT == PT_IntAP) 5590 return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(ToQT), E); 5591 if (ToT == PT_IntAPS) 5592 return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(ToQT), E); 5593 5594 // Float to integral. 5595 if (isIntegralType(ToT) || ToT == PT_Bool) 5596 return this->emitCastFloatingIntegral(ToT, E); 5597 } 5598 5599 if (isIntegralType(FromT) || FromT == PT_Bool) { 5600 if (ToT == PT_IntAP) 5601 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E); 5602 if (ToT == PT_IntAPS) 5603 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E); 5604 5605 // Integral to integral. 5606 if (isIntegralType(ToT) || ToT == PT_Bool) 5607 return FromT != ToT ? this->emitCast(FromT, ToT, E) : true; 5608 5609 if (ToT == PT_Float) { 5610 // Integral to floating. 5611 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT); 5612 return this->emitCastIntegralFloating(FromT, ToSem, getRoundingMode(E), 5613 E); 5614 } 5615 } 5616 5617 return false; 5618 } 5619 5620 /// Emits __real(SubExpr) 5621 template <class Emitter> 5622 bool Compiler<Emitter>::emitComplexReal(const Expr *SubExpr) { 5623 assert(SubExpr->getType()->isAnyComplexType()); 5624 5625 if (DiscardResult) 5626 return this->discard(SubExpr); 5627 5628 if (!this->visit(SubExpr)) 5629 return false; 5630 if (SubExpr->isLValue()) { 5631 if (!this->emitConstUint8(0, SubExpr)) 5632 return false; 5633 return this->emitArrayElemPtrPopUint8(SubExpr); 5634 } 5635 5636 // Rvalue, load the actual element. 5637 return this->emitArrayElemPop(classifyComplexElementType(SubExpr->getType()), 5638 0, SubExpr); 5639 } 5640 5641 template <class Emitter> 5642 bool Compiler<Emitter>::emitComplexBoolCast(const Expr *E) { 5643 assert(!DiscardResult); 5644 PrimType ElemT = classifyComplexElementType(E->getType()); 5645 // We emit the expression (__real(E) != 0 || __imag(E) != 0) 5646 // for us, that means (bool)E[0] || (bool)E[1] 5647 if (!this->emitArrayElem(ElemT, 0, E)) 5648 return false; 5649 if (ElemT == PT_Float) { 5650 if (!this->emitCastFloatingIntegral(PT_Bool, E)) 5651 return false; 5652 } else { 5653 if (!this->emitCast(ElemT, PT_Bool, E)) 5654 return false; 5655 } 5656 5657 // We now have the bool value of E[0] on the stack. 5658 LabelTy LabelTrue = this->getLabel(); 5659 if (!this->jumpTrue(LabelTrue)) 5660 return false; 5661 5662 if (!this->emitArrayElemPop(ElemT, 1, E)) 5663 return false; 5664 if (ElemT == PT_Float) { 5665 if (!this->emitCastFloatingIntegral(PT_Bool, E)) 5666 return false; 5667 } else { 5668 if (!this->emitCast(ElemT, PT_Bool, E)) 5669 return false; 5670 } 5671 // Leave the boolean value of E[1] on the stack. 5672 LabelTy EndLabel = this->getLabel(); 5673 this->jump(EndLabel); 5674 5675 this->emitLabel(LabelTrue); 5676 if (!this->emitPopPtr(E)) 5677 return false; 5678 if (!this->emitConstBool(true, E)) 5679 return false; 5680 5681 this->fallthrough(EndLabel); 5682 this->emitLabel(EndLabel); 5683 5684 return true; 5685 } 5686 5687 template <class Emitter> 5688 bool Compiler<Emitter>::emitComplexComparison(const Expr *LHS, const Expr *RHS, 5689 const BinaryOperator *E) { 5690 assert(E->isComparisonOp()); 5691 assert(!Initializing); 5692 assert(!DiscardResult); 5693 5694 PrimType ElemT; 5695 bool LHSIsComplex; 5696 unsigned LHSOffset; 5697 if (LHS->getType()->isAnyComplexType()) { 5698 LHSIsComplex = true; 5699 ElemT = classifyComplexElementType(LHS->getType()); 5700 LHSOffset = allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true, 5701 /*IsExtended=*/false); 5702 if (!this->visit(LHS)) 5703 return false; 5704 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E)) 5705 return false; 5706 } else { 5707 LHSIsComplex = false; 5708 PrimType LHST = classifyPrim(LHS->getType()); 5709 LHSOffset = this->allocateLocalPrimitive(LHS, LHST, true, false); 5710 if (!this->visit(LHS)) 5711 return false; 5712 if (!this->emitSetLocal(LHST, LHSOffset, E)) 5713 return false; 5714 } 5715 5716 bool RHSIsComplex; 5717 unsigned RHSOffset; 5718 if (RHS->getType()->isAnyComplexType()) { 5719 RHSIsComplex = true; 5720 ElemT = classifyComplexElementType(RHS->getType()); 5721 RHSOffset = allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true, 5722 /*IsExtended=*/false); 5723 if (!this->visit(RHS)) 5724 return false; 5725 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E)) 5726 return false; 5727 } else { 5728 RHSIsComplex = false; 5729 PrimType RHST = classifyPrim(RHS->getType()); 5730 RHSOffset = this->allocateLocalPrimitive(RHS, RHST, true, false); 5731 if (!this->visit(RHS)) 5732 return false; 5733 if (!this->emitSetLocal(RHST, RHSOffset, E)) 5734 return false; 5735 } 5736 5737 auto getElem = [&](unsigned LocalOffset, unsigned Index, 5738 bool IsComplex) -> bool { 5739 if (IsComplex) { 5740 if (!this->emitGetLocal(PT_Ptr, LocalOffset, E)) 5741 return false; 5742 return this->emitArrayElemPop(ElemT, Index, E); 5743 } 5744 return this->emitGetLocal(ElemT, LocalOffset, E); 5745 }; 5746 5747 for (unsigned I = 0; I != 2; ++I) { 5748 // Get both values. 5749 if (!getElem(LHSOffset, I, LHSIsComplex)) 5750 return false; 5751 if (!getElem(RHSOffset, I, RHSIsComplex)) 5752 return false; 5753 // And compare them. 5754 if (!this->emitEQ(ElemT, E)) 5755 return false; 5756 5757 if (!this->emitCastBoolUint8(E)) 5758 return false; 5759 } 5760 5761 // We now have two bool values on the stack. Compare those. 5762 if (!this->emitAddUint8(E)) 5763 return false; 5764 if (!this->emitConstUint8(2, E)) 5765 return false; 5766 5767 if (E->getOpcode() == BO_EQ) { 5768 if (!this->emitEQUint8(E)) 5769 return false; 5770 } else if (E->getOpcode() == BO_NE) { 5771 if (!this->emitNEUint8(E)) 5772 return false; 5773 } else 5774 return false; 5775 5776 // In C, this returns an int. 5777 if (PrimType ResT = classifyPrim(E->getType()); ResT != PT_Bool) 5778 return this->emitCast(PT_Bool, ResT, E); 5779 return true; 5780 } 5781 5782 /// When calling this, we have a pointer of the local-to-destroy 5783 /// on the stack. 5784 /// Emit destruction of record types (or arrays of record types). 5785 template <class Emitter> 5786 bool Compiler<Emitter>::emitRecordDestruction(const Record *R) { 5787 assert(R); 5788 const CXXDestructorDecl *Dtor = R->getDestructor(); 5789 if (!Dtor || Dtor->isTrivial()) 5790 return true; 5791 5792 assert(Dtor); 5793 const Function *DtorFunc = getFunction(Dtor); 5794 if (!DtorFunc) 5795 return false; 5796 assert(DtorFunc->hasThisPointer()); 5797 assert(DtorFunc->getNumParams() == 1); 5798 if (!this->emitDupPtr(SourceInfo{})) 5799 return false; 5800 return this->emitCall(DtorFunc, 0, SourceInfo{}); 5801 } 5802 /// When calling this, we have a pointer of the local-to-destroy 5803 /// on the stack. 5804 /// Emit destruction of record types (or arrays of record types). 5805 template <class Emitter> 5806 bool Compiler<Emitter>::emitDestruction(const Descriptor *Desc) { 5807 assert(Desc); 5808 assert(!Desc->isPrimitive()); 5809 assert(!Desc->isPrimitiveArray()); 5810 5811 // Arrays. 5812 if (Desc->isArray()) { 5813 const Descriptor *ElemDesc = Desc->ElemDesc; 5814 assert(ElemDesc); 5815 5816 // Don't need to do anything for these. 5817 if (ElemDesc->isPrimitiveArray()) 5818 return true; 5819 5820 // If this is an array of record types, check if we need 5821 // to call the element destructors at all. If not, try 5822 // to save the work. 5823 if (const Record *ElemRecord = ElemDesc->ElemRecord) { 5824 if (const CXXDestructorDecl *Dtor = ElemRecord->getDestructor(); 5825 !Dtor || Dtor->isTrivial()) 5826 return true; 5827 } 5828 5829 for (ssize_t I = Desc->getNumElems() - 1; I >= 0; --I) { 5830 if (!this->emitConstUint64(I, SourceInfo{})) 5831 return false; 5832 if (!this->emitArrayElemPtrUint64(SourceInfo{})) 5833 return false; 5834 if (!this->emitDestruction(ElemDesc)) 5835 return false; 5836 if (!this->emitPopPtr(SourceInfo{})) 5837 return false; 5838 } 5839 return true; 5840 } 5841 5842 assert(Desc->ElemRecord); 5843 return this->emitRecordDestruction(Desc->ElemRecord); 5844 } 5845 5846 namespace clang { 5847 namespace interp { 5848 5849 template class Compiler<ByteCodeEmitter>; 5850 template class Compiler<EvalEmitter>; 5851 5852 } // namespace interp 5853 } // namespace clang 5854