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