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