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