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