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