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