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