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