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