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