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