clang 24.0.0git
Compiler.cpp
Go to the documentation of this file.
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 "../ExprConstShared.h"
11#include "ByteCodeEmitter.h"
12#include "Context.h"
13#include "FixedPoint.h"
14#include "Floating.h"
15#include "Function.h"
16#include "InterpShared.h"
17#include "PrimType.h"
18#include "Program.h"
19#include "clang/AST/Attr.h"
21#include "llvm/Support/SaveAndRestore.h"
22
23using namespace clang;
24using namespace clang::interp;
25
26using APSInt = llvm::APSInt;
27
28namespace clang {
29namespace interp {
30
31static std::optional<bool> getBoolValue(const Expr *E) {
32 if (const auto *CE = dyn_cast_if_present<ConstantExpr>(E);
33 CE && CE->hasAPValueResult() &&
34 CE->getResultAPValueKind() == APValue::ValueKind::Int) {
35 return CE->getResultAsAPSInt().getBoolValue();
36 }
37
38 return std::nullopt;
39}
40
41/// Check if \c E has side-effects. This is used to avoid some temporary
42/// variables and is supposed to be a quick check, not exhaustive. That's why
43/// we're not using Expr::HasSideEffects().
44static bool isSideEffectFree(const Expr *E) {
47 return true;
48 if (isa<DeclRefExpr>(E))
49 return true;
50
51 return false;
52}
53
54/// Scope chain managing the variable lifetimes.
55template <class Emitter> class VariableScope {
56public:
58 : Ctx(Ctx), Parent(Ctx->VarScope), Kind(Kind) {
59 if (Parent)
60 this->LocalsAlwaysEnabled = Parent->LocalsAlwaysEnabled;
61 Ctx->VarScope = this;
62 }
63
64 virtual ~VariableScope() { Ctx->VarScope = this->Parent; }
65
66 virtual void addLocal(Scope::Local Local) {
67 llvm_unreachable("Shouldn't be called");
68 }
69 /// Like addExtended, but adds to the nearest scope of the given kind.
71 VariableScope *P = this;
72 while (P) {
73 // We found the right scope kind.
74 if (P->Kind == Kind) {
75 P->addLocal(Local);
76 return;
77 }
78 // If we reached the root scope and we're looking for a Block scope,
79 // attach it to the root instead of the current scope.
80 if (!P->Parent && Kind == ScopeKind::Block) {
81 P->addLocal(Local);
82 return;
83 }
84 P = P->Parent;
85 if (!P)
86 break;
87 }
88
89 // Add to this scope.
90 this->addLocal(Local);
91 }
92
93 virtual bool emitDestructors(const Expr *E = nullptr) { return true; }
94 virtual bool destroyLocals(const Expr *E = nullptr) { return true; }
95 virtual void forceInit() {}
96 VariableScope *getParent() const { return Parent; }
97 ScopeKind getKind() const { return Kind; }
98
99 /// Whether locals added to this scope are enabled by default.
100 /// This is almost always true, except for the two branches
101 /// of a conditional operator.
103
104protected:
105 /// Compiler instance.
107 /// Link to the parent scope.
110};
111
112/// Generic scope for local variables.
113template <class Emitter> class LocalScope : public VariableScope<Emitter> {
114public:
117
118 /// Emit a Destroy op for this scope.
119 ~LocalScope() override {
120 if (!Idx || ExplicitlyDestroyed)
121 return;
122 this->Ctx->emitDestroy(*Idx, SourceInfo{});
124 }
125 /// Explicit destruction of local variables.
126 bool destroyLocals(const Expr *E = nullptr) override {
127 if (!Idx)
128 return true;
129
130 // NB: We are *not* resetting Idx here as to allow multiple
131 // calls to destroyLocals().
132 bool Success = this->emitDestructors(E);
133 this->Ctx->emitDestroy(*Idx, E);
134 ExplicitlyDestroyed = true;
135 return Success;
136 }
137
138 void addLocal(Scope::Local Local) override {
139 if (!Idx) {
140 Idx = static_cast<unsigned>(this->Ctx->Descriptors.size());
141 this->Ctx->Descriptors.emplace_back();
142 this->Ctx->emitInitScope(*Idx, {});
143 }
144
145 Local.EnabledByDefault = this->LocalsAlwaysEnabled;
146 this->Ctx->Descriptors[*Idx].emplace_back(Local);
147 }
148
149 /// Force-initialize this scope. Usually, scopes are lazily initialized when
150 /// the first local variable is created, but in scenarios with conditonal
151 /// operators, we need to ensure scope is initialized just in case one of the
152 /// arms will create a local and the other won't. In such a case, the
153 /// InitScope() op would be part of the arm that created the local.
154 void forceInit() override {
155 if (!Idx) {
156 Idx = static_cast<unsigned>(this->Ctx->Descriptors.size());
157 this->Ctx->Descriptors.emplace_back();
158 this->Ctx->emitInitScope(*Idx, {});
159 }
160 }
161
162 bool emitDestructors(const Expr *E = nullptr) override {
163 if (!Idx)
164 return true;
165
166 // Emit destructor calls for local variables of record
167 // type with a destructor.
168 for (Scope::Local &Local : llvm::reverse(this->Ctx->Descriptors[*Idx])) {
169 if (Local.Desc->hasTrivialDtor())
170 continue;
171
172 if (!Local.EnabledByDefault) {
173 typename Emitter::LabelTy EndLabel = this->Ctx->getLabel();
174 if (!this->Ctx->emitGetLocalEnabled(Local.Offset, E))
175 return false;
176 if (!this->Ctx->jumpFalse(EndLabel, E))
177 return false;
178
179 if (!this->Ctx->emitGetPtrLocal(Local.Offset, E))
180 return false;
181
182 if (!this->Ctx->emitDestructionPop(Local.Desc, Local.Desc->getLoc()))
183 return false;
184
185 this->Ctx->fallthrough(EndLabel);
186 this->Ctx->emitLabel(EndLabel);
187 } else {
188 if (!this->Ctx->emitGetPtrLocal(Local.Offset, E))
189 return false;
190 if (!this->Ctx->emitDestructionPop(Local.Desc, Local.Desc->getLoc()))
191 return false;
192 }
193
195 }
196 return true;
197 }
198
200 if (!Idx)
201 return;
202
203 for (const Scope::Local &Local : this->Ctx->Descriptors[*Idx]) {
205 }
206 }
207
209 if (const auto *OVE =
210 llvm::dyn_cast_if_present<OpaqueValueExpr>(Local.Desc->asExpr())) {
211 this->Ctx->OpaqueExprs.erase(OVE);
212 };
213 }
214
215 /// Index of the scope in the chain.
216 UnsignedOrNone Idx = std::nullopt;
218};
219
220template <class Emitter> class ArrayIndexScope final {
221public:
222 ArrayIndexScope(Compiler<Emitter> *Ctx, uint64_t Index) : Ctx(Ctx) {
223 OldArrayIndex = Ctx->ArrayIndex;
224 Ctx->ArrayIndex = Index;
225 }
226
227 ~ArrayIndexScope() { Ctx->ArrayIndex = OldArrayIndex; }
228
229private:
231 std::optional<uint64_t> OldArrayIndex;
232};
233
234template <class Emitter> class SourceLocScope final {
235public:
236 SourceLocScope(Compiler<Emitter> *Ctx, const Expr *DefaultExpr) : Ctx(Ctx) {
237 assert(DefaultExpr);
238 // We only switch if the current SourceLocDefaultExpr is null.
239 if (!Ctx->SourceLocDefaultExpr) {
240 Enabled = true;
241 Ctx->SourceLocDefaultExpr = DefaultExpr;
242 }
243 }
244
246 if (Enabled)
247 Ctx->SourceLocDefaultExpr = nullptr;
248 }
249
250private:
252 bool Enabled = false;
253};
254
255template <class Emitter> class InitLinkScope final {
256public:
258 Ctx->InitStack.push_back(std::move(Link));
259 }
260
261 ~InitLinkScope() { this->Ctx->InitStack.pop_back(); }
262
263public:
265};
266
267template <class Emitter> class InitStackScope final {
268public:
270 : Ctx(Ctx), OldValue(Ctx->InitStackActive), Active(Active) {
271 Ctx->InitStackActive = Active;
272 if (Active)
273 Ctx->InitStack.push_back(InitLink::DIE());
274 }
275
277 this->Ctx->InitStackActive = OldValue;
278 if (Active)
279 Ctx->InitStack.pop_back();
280 }
281
282private:
284 bool OldValue;
285 bool Active;
286};
287
288/// Scope used to handle temporaries in toplevel variable declarations.
289template <class Emitter> class DeclScope final : public LocalScope<Emitter> {
290public:
292 : LocalScope<Emitter>(Ctx), Scope(Ctx->P),
293 OldInitializingDecl(Ctx->InitializingDecl) {
294 Ctx->InitializingDecl = VD;
295 Ctx->InitStack.push_back(InitLink::Decl(VD));
296 }
297
299 this->Ctx->InitializingDecl = OldInitializingDecl;
300 this->Ctx->InitStack.pop_back();
301 }
302
303private:
305 const VarDecl *OldInitializingDecl;
306};
307
308/// Scope used to handle initialization methods.
309template <class Emitter> class OptionScope final {
310public:
311 /// Root constructor, compiling or discarding primitives.
312 OptionScope(Compiler<Emitter> *Ctx, bool NewDiscardResult,
313 bool NewInitializing, bool NewToLValue)
314 : Ctx(Ctx), OldDiscardResult(Ctx->DiscardResult),
315 OldInitializing(Ctx->Initializing), OldToLValue(Ctx->ToLValue) {
316 Ctx->DiscardResult = NewDiscardResult;
317 Ctx->Initializing = NewInitializing;
318 Ctx->ToLValue = NewToLValue;
319 }
320
322 Ctx->DiscardResult = OldDiscardResult;
323 Ctx->Initializing = OldInitializing;
324 Ctx->ToLValue = OldToLValue;
325 }
326
327private:
328 /// Parent context.
330 /// Old discard flag to restore.
331 bool OldDiscardResult;
332 bool OldInitializing;
333 bool OldToLValue;
334};
335
336template <class Emitter>
337bool InitLink::emit(Compiler<Emitter> *Ctx, const Expr *E) const {
338 switch (Kind) {
339 case K_This:
340 return Ctx->emitThis(E);
341 case K_Field:
342 // We're assuming there's a base pointer on the stack already.
343 return Ctx->emitGetPtrFieldPop(Offset, E);
344 case K_Base:
345 return Ctx->emitGetPtrBasePop(Offset, false, E);
346 case K_Temp:
347 return Ctx->emitGetPtrLocal(Offset, E);
348 case K_Decl:
349 return Ctx->visitDeclRef(D, E);
350 case K_Elem:
351 if (!Ctx->emitConstUint32(Offset, E))
352 return false;
353 return Ctx->emitArrayElemPtrPopUint32(E);
354 case K_RVO:
355 return Ctx->emitRVOPtr(E);
356 case K_InitList:
357 return true;
358 default:
359 llvm_unreachable("Unhandled InitLink kind");
360 }
361 return true;
362}
363
364/// Sets the context for break/continue statements.
365template <class Emitter> class LoopScope final {
366public:
370
371 LoopScope(Compiler<Emitter> *Ctx, const Stmt *Name, LabelTy BreakLabel,
372 LabelTy ContinueLabel)
373 : Ctx(Ctx) {
374#ifndef NDEBUG
375 for (const LabelInfo &LI : Ctx->LabelInfoStack)
376 assert(LI.Name != Name);
377#endif
378
379 this->Ctx->LabelInfoStack.emplace_back(Name, BreakLabel, ContinueLabel,
380 /*DefaultLabel=*/std::nullopt,
381 Ctx->VarScope);
382 }
383
384 ~LoopScope() { this->Ctx->LabelInfoStack.pop_back(); }
385
386private:
388};
389
390// Sets the context for a switch scope, mapping labels.
391template <class Emitter> class SwitchScope final {
392public:
397
398 SwitchScope(Compiler<Emitter> *Ctx, const Stmt *Name, CaseMap &&CaseLabels,
399 LabelTy BreakLabel, OptLabelTy DefaultLabel)
400 : Ctx(Ctx), OldCaseLabels(std::move(this->Ctx->CaseLabels)) {
401#ifndef NDEBUG
402 for (const LabelInfo &LI : Ctx->LabelInfoStack)
403 assert(LI.Name != Name);
404#endif
405
406 this->Ctx->CaseLabels = std::move(CaseLabels);
407 this->Ctx->LabelInfoStack.emplace_back(Name, BreakLabel,
408 /*ContinueLabel=*/std::nullopt,
409 DefaultLabel, Ctx->VarScope);
410 }
411
413 this->Ctx->CaseLabels = std::move(OldCaseLabels);
414 this->Ctx->LabelInfoStack.pop_back();
415 }
416
417private:
419 CaseMap OldCaseLabels;
420};
421
422/// When generating code for e.g. implicit field initializers in constructors,
423/// we don't have anything to point to in case the initializer causes an error.
424/// In that case, we need to disable location tracking for the initializer so
425/// we later point to the call range instead.
426template <class Emitter> class LocOverrideScope final {
427public:
429 bool Enabled = true)
430 : Ctx(Ctx), OldFlag(Ctx->LocOverride), Enabled(Enabled) {
431
432 if (Enabled)
433 Ctx->LocOverride = NewValue;
434 }
435
437 if (Enabled)
438 Ctx->LocOverride = OldFlag;
439 }
440
441private:
443 std::optional<SourceInfo> OldFlag;
444 bool Enabled;
445};
446
447} // namespace interp
448} // namespace clang
449
450template <class Emitter>
452 const Expr *SubExpr = E->getSubExpr();
453
454 if (DiscardResult)
455 return this->delegate(SubExpr);
456
457 switch (E->getCastKind()) {
458 case CK_LValueToRValue: {
459 if (ToLValue && E->getType()->isPointerType()) {
460 assert(!DiscardResult);
461 if (!this->visit(SubExpr))
462 return false;
463 return this->emitLoadPopL(E);
464 }
465
466 if (SubExpr->getType().isVolatileQualified())
467 return this->emitInvalidCast(CastKind::Volatile, /*Fatal=*/true, E);
468
469 OptPrimType SubExprT = classify(SubExpr->getType());
470 // Try to load the value directly. This is purely a performance
471 // optimization.
472 if (SubExprT) {
473 if (const auto *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
474 const ValueDecl *D = DRE->getDecl();
475 bool IsReference = D->getType()->isReferenceType();
476
477 if (!IsReference) {
479 if (auto GlobalIndex = P.getGlobal(D))
480 return this->emitGetGlobal(*SubExprT, *GlobalIndex, E);
481 } else if (auto It = Locals.find(D); It != Locals.end()) {
482 return this->emitGetLocal(*SubExprT, It->second.Offset, E);
483 } else if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
484 if (auto It = this->Params.find(PVD); It != this->Params.end()) {
485 return this->emitGetParam(*SubExprT, It->second.Index, E);
486 }
487 }
488 }
489 }
490 }
491
492 // Prepare storage for the result.
493 if (!Initializing && !SubExprT) {
494 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
495 if (!LocalIndex)
496 return false;
497 if (!this->emitGetPtrLocal(*LocalIndex, E))
498 return false;
499 }
500
501 if (!this->visit(SubExpr))
502 return false;
503
504 if (SubExprT)
505 return this->emitLoadPop(*SubExprT, E);
506
507 // If the subexpr type is not primitive, we need to perform a copy here.
508 // This happens for example in C when dereferencing a pointer of struct
509 // type.
510 return this->emitMemcpy(E);
511 }
512
513 case CK_DerivedToBaseMemberPointer: {
514 if (E->containsErrors())
515 return false;
516 assert(classifyPrim(E) == PT_MemberPtr);
517 assert(classifyPrim(SubExpr) == PT_MemberPtr);
518
519 if (!this->delegate(SubExpr))
520 return false;
521
522 const CXXRecordDecl *CurDecl = SubExpr->getType()
524 ->getMostRecentCXXRecordDecl();
525 for (const CXXBaseSpecifier *B : E->path()) {
526 const CXXRecordDecl *ToDecl = B->getType()->getAsCXXRecordDecl();
527 unsigned DerivedOffset = Ctx.collectBaseOffset(ToDecl, CurDecl);
528
529 if (!this->emitCastMemberPtrBasePop(DerivedOffset, ToDecl, E))
530 return false;
531 CurDecl = ToDecl;
532 }
533
534 return true;
535 }
536
537 case CK_BaseToDerivedMemberPointer: {
538 if (E->containsErrors())
539 return false;
540 assert(classifyPrim(E) == PT_MemberPtr);
541 assert(classifyPrim(SubExpr) == PT_MemberPtr);
542
543 if (!this->delegate(SubExpr))
544 return false;
545
546 const CXXRecordDecl *CurDecl = SubExpr->getType()
548 ->getMostRecentCXXRecordDecl();
549 // Base-to-derived member pointer casts store the path in derived-to-base
550 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
551 // the wrong end of the derived->base arc, so stagger the path by one class.
552 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
553 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
554 PathI != PathE; ++PathI) {
555 const CXXRecordDecl *ToDecl = (*PathI)->getType()->getAsCXXRecordDecl();
556 unsigned DerivedOffset = Ctx.collectBaseOffset(CurDecl, ToDecl);
557
558 if (!this->emitCastMemberPtrDerivedPop(-DerivedOffset, ToDecl, E))
559 return false;
560 CurDecl = ToDecl;
561 }
562
563 const CXXRecordDecl *ToDecl =
564 E->getType()->castAs<MemberPointerType>()->getMostRecentCXXRecordDecl();
565 assert(ToDecl != CurDecl);
566 unsigned DerivedOffset = Ctx.collectBaseOffset(CurDecl, ToDecl);
567
568 if (!this->emitCastMemberPtrDerivedPop(-DerivedOffset, ToDecl, E))
569 return false;
570
571 return true;
572 }
573
574 case CK_UncheckedDerivedToBase:
575 case CK_DerivedToBase: {
576 if (!this->delegate(SubExpr))
577 return false;
578
579 const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
580 if (const auto *PT = dyn_cast<PointerType>(Ty))
581 return PT->getPointeeType()->getAsCXXRecordDecl();
582 return Ty->getAsCXXRecordDecl();
583 };
584
585 // FIXME: We can express a series of non-virtual casts as a single
586 // GetPtrBasePop op.
587 QualType CurType = SubExpr->getType();
588 for (const CXXBaseSpecifier *B : E->path()) {
589 if (B->isVirtual()) {
590 if (!this->emitGetPtrVirtBasePop(extractRecordDecl(B->getType()), E))
591 return false;
592 CurType = B->getType();
593 } else {
594 unsigned DerivedOffset = collectBaseOffset(B->getType(), CurType);
595 if (!this->emitGetPtrBasePop(
596 DerivedOffset, /*NullOK=*/E->getType()->isPointerType(), E))
597 return false;
598 CurType = B->getType();
599 }
600 }
601
602 return true;
603 }
604
605 case CK_BaseToDerived: {
606 if (!this->delegate(SubExpr))
607 return false;
608 unsigned DerivedOffset =
609 collectBaseOffset(SubExpr->getType(), E->getType());
610
611 const Type *TargetType = E->getType().getTypePtr();
612 if (TargetType->isPointerOrReferenceType())
613 TargetType = TargetType->getPointeeType().getTypePtr();
614 return this->emitGetPtrDerivedPop(DerivedOffset,
615 /*NullOK=*/E->getType()->isPointerType(),
616 TargetType, E);
617 }
618
619 case CK_FloatingCast: {
620 // HLSL uses CK_FloatingCast to cast between vectors.
621 if (E->getType()->isVectorType())
622 return this->emitVectorConversion(E->getSubExpr(), E);
623 if (!SubExpr->getType()->isFloatingType() ||
624 !E->getType()->isFloatingType())
625 return false;
626 if (!this->visit(SubExpr))
627 return false;
628 const auto *TargetSemantics = &Ctx.getFloatSemantics(E->getType());
629 return this->emitCastFP(TargetSemantics, getRoundingMode(E), E);
630 }
631
632 case CK_IntegralToFloating: {
633 if (E->getType()->isVectorType())
634 return this->emitVectorConversion(E->getSubExpr(), E);
635 if (!E->getType()->isRealFloatingType())
636 return false;
637 if (!this->visit(SubExpr))
638 return false;
639 const auto *TargetSemantics = &Ctx.getFloatSemantics(E->getType());
640 return this->emitCastIntegralFloating(classifyPrim(SubExpr),
641 TargetSemantics, getFPOptions(E), E);
642 }
643
644 case CK_FloatingToBoolean: {
645 if (E->getType()->isVectorType())
646 return this->emitVectorConversion(E->getSubExpr(), E);
647 if (!SubExpr->getType()->isRealFloatingType() ||
649 return false;
650 if (const auto *FL = dyn_cast<FloatingLiteral>(SubExpr))
651 return this->emitConstBool(FL->getValue().isNonZero(), E);
652 if (!this->visit(SubExpr))
653 return false;
654 return this->emitCastFloatingIntegralBool(getFPOptions(E), E);
655 }
656
657 case CK_FloatingToIntegral: {
658 if (E->getType()->isVectorType())
659 return this->emitVectorConversion(E->getSubExpr(), E);
661 return false;
662 if (!this->visit(SubExpr))
663 return false;
664 PrimType ToT = classifyPrim(E);
665 if (ToT == PT_IntAP)
666 return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(E->getType()),
667 getFPOptions(E), E);
668 if (ToT == PT_IntAPS)
669 return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(E->getType()),
670 getFPOptions(E), E);
671
672 return this->emitCastFloatingIntegral(ToT, getFPOptions(E), E);
673 }
674
675 case CK_NullToPointer:
676 case CK_NullToMemberPointer: {
677 if (!this->discard(SubExpr))
678 return false;
679 uint64_t Val = Ctx.getASTContext().getTargetNullPointerValue(E->getType());
680 return this->emitNull(classifyPrim(E->getType()), Val,
681 E->getType().getTypePtr(), E);
682 }
683
684 case CK_PointerToIntegral: {
685 if (!this->visit(SubExpr))
686 return false;
687
688 // If SubExpr doesn't result in a pointer, make it one.
689 if (PrimType FromT = classifyPrim(SubExpr->getType()); FromT != PT_Ptr) {
690 assert(isPtrType(FromT));
691 if (!this->emitDecayPtr(FromT, PT_Ptr, E))
692 return false;
693 }
694
696 if (T == PT_IntAP)
697 return this->emitCastPointerIntegralAP(Ctx.getBitWidth(E->getType()), E);
698 if (T == PT_IntAPS)
699 return this->emitCastPointerIntegralAPS(Ctx.getBitWidth(E->getType()), E);
700 return this->emitCastPointerIntegral(T, E);
701 }
702
703 case CK_ArrayToPointerDecay: {
704 if (!this->visit(SubExpr))
705 return false;
706 return this->emitArrayDecay(E);
707 }
708
709 case CK_IntegralToPointer: {
710 QualType IntType = SubExpr->getType();
711 assert(IntType->isIntegralOrEnumerationType());
712 if (!this->visit(SubExpr))
713 return false;
714 // FIXME: I think the discard is wrong since the int->ptr cast might cause a
715 // diagnostic.
716 PrimType T = classifyPrim(IntType);
717 if (!this->emitGetIntPtr(T, E->getType().getTypePtr(), E))
718 return false;
719
720 QualType PtrType = E->getType();
721 PrimType DestPtrT = classifyPrim(PtrType);
722 if (DestPtrT == PT_Ptr)
723 return true;
724
725 // In case we're converting the integer to a non-Pointer.
726 return this->emitDecayPtr(PT_Ptr, DestPtrT, E);
727 }
728
729 case CK_AtomicToNonAtomic:
730 case CK_ConstructorConversion:
731 case CK_FunctionToPointerDecay:
732 case CK_NonAtomicToAtomic:
733 case CK_NoOp:
734 case CK_UserDefinedConversion:
735 case CK_AddressSpaceConversion:
736 case CK_CPointerToObjCPointerCast:
737 return this->delegate(SubExpr);
738
739 case CK_BitCast: {
740 if (E->containsErrors())
741 return false;
742 QualType ETy = E->getType();
743 // Reject bitcasts to atomic types.
744 if (ETy->isAtomicType()) {
745 if (!this->discard(SubExpr))
746 return false;
747 return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, E);
748 }
749 QualType SubExprTy = SubExpr->getType();
750 OptPrimType FromT = classify(SubExprTy);
751 // Casts from integer/vector to vector.
752 if (E->getType()->isVectorType())
753 return this->emitBuiltinBitCast(E);
754
755 OptPrimType ToT = classify(E->getType());
756 if (!FromT || !ToT)
757 return false;
758
759 assert(isPtrType(*FromT));
760 assert(isPtrType(*ToT));
761 bool SrcIsVoidPtr = SubExprTy->isVoidPointerType();
762 if (FromT == ToT) {
763 if (E->getType()->isVoidPointerType() &&
764 !SubExprTy->isFunctionPointerType()) {
765 return this->delegate(SubExpr);
766 }
767
768 if (!this->visit(SubExpr))
769 return false;
770 if (!this->emitCheckBitCast(ETy->getPointeeType().getTypePtr(),
771 SrcIsVoidPtr, E))
772 return false;
773
774 if (E->getType()->isFunctionPointerType() ||
775 SubExprTy->isFunctionPointerType()) {
776 return this->emitFnPtrCast(E);
777 }
778 if (FromT == PT_Ptr)
779 return this->emitPtrPtrCast(SubExprTy->isVoidPointerType(), E);
780 return true;
781 }
782
783 if (!this->visit(SubExpr))
784 return false;
785 return this->emitDecayPtr(*FromT, *ToT, E);
786 }
787 case CK_IntegralToBoolean:
788 case CK_FixedPointToBoolean: {
789 if (E->getType()->isVectorType())
790 return this->emitVectorConversion(E->getSubExpr(), E);
791 // HLSL uses this to cast to one-element vectors.
792 OptPrimType FromT = classify(SubExpr->getType());
793 if (!FromT)
794 return false;
795
796 if (const auto *IL = dyn_cast<IntegerLiteral>(SubExpr))
797 return this->emitConst(IL->getValue(), E);
798 if (!this->visit(SubExpr))
799 return false;
800 return this->emitCast(*FromT, classifyPrim(E), E);
801 }
802
803 case CK_IntegralCast:
804 if (E->getType()->isVectorType())
805 return this->emitVectorConversion(E->getSubExpr(), E);
806 [[fallthrough]];
807 case CK_BooleanToSignedIntegral: {
808 OptPrimType FromT = classify(SubExpr->getType());
809 OptPrimType ToT = classify(E->getType());
810 if (!FromT || !ToT)
811 return false;
812
813 // Try to emit a casted known constant value directly.
814 if (const auto *IL = dyn_cast<IntegerLiteral>(SubExpr)) {
815 if (ToT != PT_IntAP && ToT != PT_IntAPS && FromT != PT_IntAP &&
816 FromT != PT_IntAPS && !E->getType()->isEnumeralType())
817 return this->emitConst(APSInt(IL->getValue(), !isSignedType(*FromT)),
818 E);
819 if (!this->emitConst(IL->getValue(), SubExpr))
820 return false;
821 } else {
822 if (!this->visit(SubExpr))
823 return false;
824 }
825
826 // Possibly diagnose casts to enum types if the target type does not
827 // have a fixed size.
828 if (Ctx.getLangOpts().CPlusPlus && E->getType()->isEnumeralType()) {
829 const auto *ED = E->getType()->castAsEnumDecl();
830 if (!ED->isFixed()) {
831 if (!this->emitCheckEnumValue(*FromT, ED, E))
832 return false;
833 }
834 }
835
836 if (ToT == PT_IntAP) {
837 if (!this->emitCastAP(*FromT, Ctx.getBitWidth(E->getType()), E))
838 return false;
839 } else if (ToT == PT_IntAPS) {
840 if (!this->emitCastAPS(*FromT, Ctx.getBitWidth(E->getType()), E))
841 return false;
842 } else {
843 if (FromT == ToT)
844 return true;
845 if (!this->emitCast(*FromT, *ToT, E))
846 return false;
847 }
848 if (E->getCastKind() == CK_BooleanToSignedIntegral)
849 return this->emitNeg(*ToT, E);
850 return true;
851 }
852
853 case CK_PointerToBoolean:
854 if (!this->visit(SubExpr))
855 return false;
856 return this->emitIsNonNullPtr(E);
857
858 case CK_MemberPointerToBoolean:
859 if (!this->visit(SubExpr))
860 return false;
861 return this->emitIsNonNullMemberPtr(E);
862
863 case CK_IntegralComplexToBoolean:
864 case CK_FloatingComplexToBoolean: {
865 if (!this->visit(SubExpr))
866 return false;
867 return this->emitComplexBoolCast(SubExpr);
868 }
869
870 case CK_IntegralComplexToReal:
871 case CK_FloatingComplexToReal:
872 return this->emitComplexReal(SubExpr);
873
874 case CK_IntegralRealToComplex:
875 case CK_FloatingRealToComplex: {
876 // We're creating a complex value here, so we need to
877 // allocate storage for it.
878 if (!Initializing) {
879 UnsignedOrNone LocalIndex = allocateTemporary(E);
880 if (!LocalIndex)
881 return false;
882 if (!this->emitGetPtrLocal(*LocalIndex, E))
883 return false;
884 }
885
886 PrimType T = classifyPrim(SubExpr->getType());
887 // Init the complex value to {SubExpr, 0}.
888 if (!this->visitArrayElemInit(0, SubExpr, T))
889 return false;
890 // Zero-init the second element.
891 if (!this->visitZeroInitializer(T, SubExpr->getType(), SubExpr))
892 return false;
893 return this->emitInitElem(T, 1, SubExpr);
894 }
895
896 case CK_IntegralComplexCast:
897 case CK_FloatingComplexCast:
898 case CK_IntegralComplexToFloatingComplex:
899 case CK_FloatingComplexToIntegralComplex: {
900 assert(E->getType()->isAnyComplexType());
901 assert(SubExpr->getType()->isAnyComplexType());
902 if (!Initializing) {
903 UnsignedOrNone LocalIndex = allocateLocal(E);
904 if (!LocalIndex)
905 return false;
906 if (!this->emitGetPtrLocal(*LocalIndex, E))
907 return false;
908 }
909
910 // Location for the SubExpr.
911 // Since SubExpr is of complex type, visiting it results in a pointer
912 // anyway, so we just create a temporary pointer variable.
913 unsigned SubExprOffset =
914 allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
915 if (!this->visit(SubExpr))
916 return false;
917 if (!this->emitSetLocal(PT_Ptr, SubExprOffset, E))
918 return false;
919
920 PrimType SourceElemT = classifyComplexElementType(SubExpr->getType());
921 QualType DestElemType =
922 E->getType()->getAs<ComplexType>()->getElementType();
923 PrimType DestElemT = classifyPrim(DestElemType);
924 // Cast both elements individually.
925 for (unsigned I = 0; I != 2; ++I) {
926 if (!this->emitGetLocal(PT_Ptr, SubExprOffset, E))
927 return false;
928 if (!this->emitArrayElemPop(SourceElemT, I, E))
929 return false;
930
931 // Do the cast.
932 if (!this->emitPrimCast(SourceElemT, DestElemT, DestElemType, E))
933 return false;
934
935 // Save the value.
936 if (!this->emitInitElem(DestElemT, I, E))
937 return false;
938 }
939 return true;
940 }
941
942 case CK_VectorSplat: {
943 assert(!canClassify(E->getType()));
944 assert(E->getType()->isVectorType());
945
946 if (!canClassify(SubExpr->getType()))
947 return false;
948
949 if (!Initializing) {
950 UnsignedOrNone LocalIndex = allocateLocal(E);
951 if (!LocalIndex)
952 return false;
953 if (!this->emitGetPtrLocal(*LocalIndex, E))
954 return false;
955 }
956
957 const auto *VT = E->getType()->getAs<VectorType>();
958 PrimType ElemT = classifyPrim(SubExpr->getType());
959 unsigned ElemOffset =
960 allocateLocalPrimitive(SubExpr, ElemT, /*IsConst=*/true);
961
962 // Prepare a local variable for the scalar value.
963 if (!this->visit(SubExpr))
964 return false;
965 if (classifyPrim(SubExpr) == PT_Ptr && !this->emitLoadPop(ElemT, E))
966 return false;
967
968 if (!this->emitSetLocal(ElemT, ElemOffset, E))
969 return false;
970
971 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
972 if (!this->emitGetLocal(ElemT, ElemOffset, E))
973 return false;
974 if (!this->emitInitElem(ElemT, I, E))
975 return false;
976 }
977
978 return true;
979 }
980
981 case CK_HLSLVectorTruncation: {
982 assert(SubExpr->getType()->isVectorType());
983 if (OptPrimType ResultT = classify(E)) {
984 assert(!DiscardResult);
985 // Result must be either a float or integer. Take the first element.
986 if (!this->visit(SubExpr))
987 return false;
988 return this->emitArrayElemPop(*ResultT, 0, E);
989 }
990 // Otherwise, this truncates from one vector type to another.
991 assert(E->getType()->isVectorType());
992
993 if (!Initializing) {
994 UnsignedOrNone LocalIndex = allocateTemporary(E);
995 if (!LocalIndex)
996 return false;
997 if (!this->emitGetPtrLocal(*LocalIndex, E))
998 return false;
999 }
1000 unsigned ToSize = E->getType()->getAs<VectorType>()->getNumElements();
1001 assert(SubExpr->getType()->getAs<VectorType>()->getNumElements() > ToSize);
1002 if (!this->visit(SubExpr))
1003 return false;
1004 return this->emitCopyArray(classifyVectorElementType(E->getType()), 0, 0,
1005 ToSize, E);
1006 };
1007
1008 case CK_IntegralToFixedPoint: {
1009 if (!this->visit(SubExpr))
1010 return false;
1011
1012 auto Sem =
1013 Ctx.getASTContext().getFixedPointSemantics(E->getType()).toOpaqueInt();
1014 if (!this->emitCastIntegralFixedPoint(classifyPrim(SubExpr->getType()), Sem,
1015 E))
1016 return false;
1017 if (DiscardResult)
1018 return this->emitPopFixedPoint(E);
1019 return true;
1020 }
1021 case CK_FloatingToFixedPoint: {
1022 if (!this->visit(SubExpr))
1023 return false;
1024
1025 auto Sem =
1026 Ctx.getASTContext().getFixedPointSemantics(E->getType()).toOpaqueInt();
1027 if (!this->emitCastFloatingFixedPoint(Sem, E))
1028 return false;
1029 if (DiscardResult)
1030 return this->emitPopFixedPoint(E);
1031 return true;
1032 }
1033 case CK_FixedPointToFloating: {
1034 if (!this->visit(SubExpr))
1035 return false;
1036 const auto *TargetSemantics = &Ctx.getFloatSemantics(E->getType());
1037 if (!this->emitCastFixedPointFloating(TargetSemantics, E))
1038 return false;
1039 if (DiscardResult)
1040 return this->emitPopFloat(E);
1041 return true;
1042 }
1043 case CK_FixedPointToIntegral: {
1044 if (!this->visit(SubExpr))
1045 return false;
1046 PrimType IntegralT = classifyPrim(E->getType());
1047 if (!this->emitCastFixedPointIntegral(IntegralT, E))
1048 return false;
1049 if (DiscardResult)
1050 return this->emitPop(IntegralT, E);
1051 return true;
1052 }
1053 case CK_FixedPointCast: {
1054 if (!this->visit(SubExpr))
1055 return false;
1056 auto Sem =
1057 Ctx.getASTContext().getFixedPointSemantics(E->getType()).toOpaqueInt();
1058 if (!this->emitCastFixedPoint(Sem, E))
1059 return false;
1060 if (DiscardResult)
1061 return this->emitPopFixedPoint(E);
1062 return true;
1063 }
1064
1065 case CK_ToVoid:
1066 return discard(SubExpr);
1067
1068 case CK_Dynamic:
1069 llvm_unreachable("CXXDynamicCastExpr has its own function");
1070
1071 case CK_LValueBitCast:
1072 if (!this->emitInvalidCast(CastKind::ReinterpretLike, /*Fatal=*/false, E))
1073 return false;
1074 return this->delegate(SubExpr);
1075
1076 case CK_HLSLArrayRValue: {
1077 // Non-decaying array rvalue cast - creates an rvalue copy of an lvalue
1078 // array, similar to LValueToRValue for composite types.
1079 if (!Initializing) {
1080 UnsignedOrNone LocalIndex = allocateLocal(E);
1081 if (!LocalIndex)
1082 return false;
1083 if (!this->emitGetPtrLocal(*LocalIndex, E))
1084 return false;
1085 }
1086 if (!this->visit(SubExpr))
1087 return false;
1088 return this->emitMemcpy(E);
1089 }
1090
1091 case CK_HLSLMatrixTruncation: {
1092 assert(SubExpr->getType()->isConstantMatrixType());
1093 if (OptPrimType ResultT = classify(E)) {
1094 assert(!DiscardResult);
1095 // Result must be either a float or integer. Take the first element.
1096 if (!this->visit(SubExpr))
1097 return false;
1098 return this->emitArrayElemPop(*ResultT, 0, E);
1099 }
1100 // Otherwise, this truncates to a a constant matrix type.
1101 assert(E->getType()->isConstantMatrixType());
1102
1103 if (!Initializing) {
1104 UnsignedOrNone LocalIndex = allocateTemporary(E);
1105 if (!LocalIndex)
1106 return false;
1107 if (!this->emitGetPtrLocal(*LocalIndex, E))
1108 return false;
1109 }
1110 unsigned ToSize =
1111 E->getType()->getAs<ConstantMatrixType>()->getNumElementsFlattened();
1112 if (!this->visit(SubExpr))
1113 return false;
1114 return this->emitCopyArray(classifyMatrixElementType(SubExpr->getType()), 0,
1115 0, ToSize, E);
1116 }
1117
1118 case CK_HLSLAggregateSplatCast: {
1119 // Aggregate splat cast: convert a scalar value to one of an aggregate type
1120 // by replicating and casting the scalar to every element of the destination
1121 // aggregate (vector, matrix, array, or struct).
1122 assert(canClassify(SubExpr->getType()));
1123
1124 if (!Initializing) {
1125 UnsignedOrNone LocalIndex = allocateLocal(E);
1126 if (!LocalIndex)
1127 return false;
1128 if (!this->emitGetPtrLocal(*LocalIndex, E))
1129 return false;
1130 }
1131
1132 // The scalar to be splatted is stored in a local to be repeatedly loaded
1133 // once for every scalar element of the destination.
1134 PrimType SrcElemT = classifyPrim(SubExpr->getType());
1135 unsigned SrcOffset =
1136 allocateLocalPrimitive(SubExpr, SrcElemT, /*IsConst=*/true);
1137
1138 if (!this->visit(SubExpr))
1139 return false;
1140 if (!this->emitSetLocal(SrcElemT, SrcOffset, E))
1141 return false;
1142
1143 // Recursively splat the scalar into every element of the destination.
1144 return emitHLSLAggregateSplat(SrcElemT, SrcOffset, E->getType(), E);
1145 }
1146
1147 case CK_HLSLElementwiseCast: {
1148 // Elementwise cast: flatten the elements of one aggregate source type and
1149 // store to a destination scalar or aggregate type of the same or fewer
1150 // number of elements. Casts are inserted element-wise to convert each
1151 // source scalar element to its corresponding destination scalar element.
1152 QualType SrcType = SubExpr->getType();
1153 QualType DestType = E->getType();
1154
1155 if (OptPrimType DestT = classify(DestType)) {
1156 // When the destination is a scalar, we only need the first scalar
1157 // element of the source.
1158 unsigned SrcPtrOffset =
1159 allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
1160 if (!this->visit(SubExpr))
1161 return false;
1162 if (!this->emitSetLocal(PT_Ptr, SrcPtrOffset, E))
1163 return false;
1164
1166 if (!emitHLSLFlattenAggregate(SrcType, SrcPtrOffset, Elements, 1, E))
1167 return false;
1168 if (Elements.empty())
1169 return false;
1170
1171 const HLSLFlatElement &Src = Elements[0];
1172 if (!this->emitGetLocal(Src.Type, Src.LocalOffset, E))
1173 return false;
1174 return this->emitPrimCast(Src.Type, *DestT, DestType, E);
1175 }
1176
1177 if (!Initializing) {
1178 UnsignedOrNone LocalIndex = allocateLocal(E);
1179 if (!LocalIndex)
1180 return false;
1181 if (!this->emitGetPtrLocal(*LocalIndex, E))
1182 return false;
1183 }
1184
1185 unsigned SrcOffset =
1186 allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
1187 if (!this->visit(SubExpr))
1188 return false;
1189 if (!this->emitSetLocal(PT_Ptr, SrcOffset, E))
1190 return false;
1191
1192 // Only flatten as many source elements as the destination requires.
1193 unsigned ElemCount = countHLSLFlatElements(DestType);
1194
1196 Elements.reserve(ElemCount);
1197 if (!emitHLSLFlattenAggregate(SrcType, SrcOffset, Elements, ElemCount, E))
1198 return false;
1199
1200 // Sema is expected to reject an elementwise cast whose source has fewer
1201 // scalar elements than the destination.
1202 assert(Elements.size() == ElemCount &&
1203 "Source type has fewer scalar elements than the destination type");
1204
1205 return emitHLSLConstructAggregate(DestType, Elements, E);
1206 }
1207
1208 case CK_ToUnion: {
1209 const FieldDecl *UnionField = E->getTargetUnionField();
1210 const Record *R = this->getRecord(E->getType());
1211 assert(R);
1212 const Record::Field *RF = R->getField(UnionField);
1213 QualType FieldType = RF->Decl->getType();
1214
1215 if (OptPrimType PT = classify(FieldType)) {
1216 if (!this->visit(SubExpr))
1217 return false;
1218 if (RF->isBitField())
1219 return this->emitInitBitFieldActivate(*PT, RF->Offset, RF->bitWidth(),
1220 E);
1221 return this->emitInitFieldActivate(*PT, RF->Offset, E);
1222 }
1223
1224 if (!this->emitGetPtrField(RF->Offset, E))
1225 return false;
1226 if (!this->emitActivate(E))
1227 return false;
1228 return this->visitInitializerPop(SubExpr);
1229 }
1230
1231 default:
1232 return this->emitInvalid(E);
1233 }
1234 llvm_unreachable("Unhandled clang::CastKind enum");
1235}
1236
1237template <class Emitter>
1239 return this->emitBuiltinBitCast(E);
1240}
1241
1242template <class Emitter>
1244 if (DiscardResult)
1245 return true;
1246
1247 return this->emitConst(LE->getValue(), LE);
1248}
1249
1250template <class Emitter>
1252 if (DiscardResult)
1253 return true;
1254
1255 APFloat F = E->getValue();
1256 return this->emitFloat(F, E);
1257}
1258
1259template <class Emitter>
1261 assert(E->getType()->isAnyComplexType());
1262 if (DiscardResult)
1263 return true;
1264
1265 if (!Initializing) {
1266 UnsignedOrNone LocalIndex = allocateTemporary(E);
1267 if (!LocalIndex)
1268 return false;
1269 if (!this->emitGetPtrLocal(*LocalIndex, E))
1270 return false;
1271 }
1272
1273 const Expr *SubExpr = E->getSubExpr();
1274 PrimType SubExprT = classifyPrim(SubExpr->getType());
1275
1276 if (!this->visitZeroInitializer(SubExprT, SubExpr->getType(), SubExpr))
1277 return false;
1278 if (!this->emitInitElem(SubExprT, 0, SubExpr))
1279 return false;
1280 return this->visitArrayElemInit(1, SubExpr, SubExprT);
1281}
1282
1283template <class Emitter>
1285 assert(E->getType()->isFixedPointType());
1286 assert(classifyPrim(E) == PT_FixedPoint);
1287
1288 if (DiscardResult)
1289 return true;
1290
1291 auto Sem = Ctx.getASTContext().getFixedPointSemantics(E->getType());
1292 APInt Value = E->getValue();
1293 return this->emitConstFixedPoint(FixedPoint(Value, Sem), E);
1294}
1295
1296template <class Emitter>
1298 return this->delegate(E->getSubExpr());
1299}
1300
1301template <class Emitter>
1303 // Need short-circuiting for these.
1304 if (E->isLogicalOp() && !E->getType()->isVectorType())
1305 return this->VisitLogicalBinOp(E);
1306
1307 const Expr *LHS = E->getLHS();
1308 const Expr *RHS = E->getRHS();
1309
1310 // Handle comma operators. Just discard the LHS
1311 // and delegate to RHS.
1312 if (E->isCommaOp()) {
1313 if (!this->discard(LHS))
1314 return false;
1315 if (RHS->getType()->isVoidType())
1316 return this->discard(RHS);
1317
1318 return this->delegate(RHS);
1319 }
1320
1321 if (E->getType()->isAnyComplexType())
1322 return this->VisitComplexBinOp(E);
1323 if (E->getType()->isVectorType())
1324 return this->VisitVectorBinOp(E);
1325 if ((LHS->getType()->isAnyComplexType() ||
1326 RHS->getType()->isAnyComplexType()) &&
1327 E->isComparisonOp())
1328 return this->emitComplexComparison(LHS, RHS, E);
1329 if (LHS->getType()->isFixedPointType() || RHS->getType()->isFixedPointType())
1330 return this->VisitFixedPointBinOp(E);
1331
1332 if (E->isPtrMemOp()) {
1333 if (E->containsErrors())
1334 return false;
1335
1336 if (!this->visit(LHS))
1337 return false;
1338
1339 if (!this->visit(RHS))
1340 return false;
1341
1342 if (!this->emitToMemberPtr(E))
1343 return false;
1344
1345 if (classifyPrim(E) == PT_MemberPtr)
1346 return true;
1347
1348 if (!this->emitCastMemberPtrPtr(E))
1349 return false;
1350 return DiscardResult ? this->emitPopPtr(E) : true;
1351 }
1352
1353 // Typecheck the args.
1354 OptPrimType LT = classify(LHS);
1355 OptPrimType RT = classify(RHS);
1356 OptPrimType T = classify(E->getType());
1357
1358 // Special case for C++'s three-way/spaceship operator <=>, which
1359 // returns a std::{strong,weak,partial}_ordering (which is a class, so doesn't
1360 // have a PrimType).
1361 if (!T && E->getOpcode() == BO_Cmp) {
1362 if (DiscardResult)
1363 return true;
1364 const ComparisonCategoryInfo *CmpInfo =
1365 Ctx.getASTContext().CompCategories.lookupInfoForType(E->getType());
1366 assert(CmpInfo);
1367
1368 // We need a temporary variable holding our return value.
1369 if (!Initializing) {
1370 UnsignedOrNone ResultIndex = this->allocateLocal(E);
1371 if (!this->emitGetPtrLocal(*ResultIndex, E))
1372 return false;
1373 }
1374
1375 if (!visit(LHS) || !visit(RHS))
1376 return false;
1377
1378 return this->emitCMP3(*LT, CmpInfo, E);
1379 }
1380
1381 if (!LT || !RT || !T)
1382 return false;
1383
1384 // Pointer arithmetic special case.
1385 if (E->getOpcode() == BO_Add || E->getOpcode() == BO_Sub) {
1386 if (isPtrType(*T) || (isPtrType(*LT) && isPtrType(*RT)))
1387 return this->VisitPointerArithBinOp(E);
1388 }
1389
1390 if (E->getOpcode() == BO_Assign)
1391 return this->visitAssignment(LHS, RHS, E);
1392
1393 if (!visit(LHS) || !visit(RHS))
1394 return false;
1395
1396 // For languages such as C, cast the result of one
1397 // of our comparision opcodes to T (which is usually int).
1398 auto MaybeCastToBool = [this, T, E](bool Result) {
1399 if (!Result)
1400 return false;
1401 if (DiscardResult)
1402 return this->emitPopBool(E);
1403 if (T != PT_Bool)
1404 return this->emitCast(PT_Bool, *T, E);
1405 return true;
1406 };
1407
1408 auto Discard = [this, T, E](bool Result) {
1409 if (!Result)
1410 return false;
1411 return DiscardResult ? this->emitPop(*T, E) : true;
1412 };
1413
1414 switch (E->getOpcode()) {
1415 case BO_EQ:
1416 return MaybeCastToBool(this->emitEQ(*LT, E));
1417 case BO_NE:
1418 return MaybeCastToBool(this->emitNE(*LT, E));
1419 case BO_LT:
1420 return MaybeCastToBool(this->emitLT(*LT, E));
1421 case BO_LE:
1422 return MaybeCastToBool(this->emitLE(*LT, E));
1423 case BO_GT:
1424 return MaybeCastToBool(this->emitGT(*LT, E));
1425 case BO_GE:
1426 return MaybeCastToBool(this->emitGE(*LT, E));
1427 case BO_Sub:
1428 if (E->getType()->isFloatingType())
1429 return Discard(this->emitSubf(getFPOptions(E), E));
1430 return Discard(this->emitSub(*T, E));
1431 case BO_Add:
1432 if (E->getType()->isFloatingType())
1433 return Discard(this->emitAddf(getFPOptions(E), E));
1434 return Discard(this->emitAdd(*T, E));
1435 case BO_Mul:
1436 if (E->getType()->isFloatingType())
1437 return Discard(this->emitMulf(getFPOptions(E), E));
1438 return Discard(this->emitMul(*T, E));
1439 case BO_Rem:
1440 return Discard(this->emitRem(*T, E));
1441 case BO_Div:
1442 if (E->getType()->isFloatingType())
1443 return Discard(this->emitDivf(getFPOptions(E), E));
1444 return Discard(this->emitDiv(*T, E));
1445 case BO_And:
1446 return Discard(this->emitBitAnd(*T, E));
1447 case BO_Or:
1448 return Discard(this->emitBitOr(*T, E));
1449 case BO_Shl:
1450 return Discard(this->emitShl(*LT, *RT, E));
1451 case BO_Shr:
1452 return Discard(this->emitShr(*LT, *RT, E));
1453 case BO_Xor:
1454 return Discard(this->emitBitXor(*T, E));
1455 case BO_LOr:
1456 case BO_LAnd:
1457 llvm_unreachable("Already handled earlier");
1458 default:
1459 return false;
1460 }
1461
1462 llvm_unreachable("Unhandled binary op");
1463}
1464
1465/// Perform addition/subtraction of a pointer and an integer or
1466/// subtraction of two pointers.
1467template <class Emitter>
1469 BinaryOperatorKind Op = E->getOpcode();
1470 const Expr *LHS = E->getLHS();
1471 const Expr *RHS = E->getRHS();
1472
1473 if ((Op != BO_Add && Op != BO_Sub) ||
1474 (!LHS->getType()->isPointerType() && !RHS->getType()->isPointerType()))
1475 return false;
1476
1477 OptPrimType LT = classify(LHS);
1478 OptPrimType RT = classify(RHS);
1479
1480 if (!LT || !RT)
1481 return false;
1482
1483 // Visit the given pointer expression and optionally convert to a PT_Ptr.
1484 auto visitAsPointer = [&](const Expr *E, PrimType T) -> bool {
1485 if (!this->visit(E))
1486 return false;
1487 if (T != PT_Ptr)
1488 return this->emitDecayPtr(T, PT_Ptr, E);
1489 return true;
1490 };
1491
1492 if (LHS->getType()->isPointerType() && RHS->getType()->isPointerType()) {
1493 if (Op != BO_Sub)
1494 return false;
1495
1496 assert(E->getType()->isIntegerType());
1497 if (!visitAsPointer(RHS, *RT) || !visitAsPointer(LHS, *LT))
1498 return false;
1499
1500 QualType ElemType = LHS->getType()->getPointeeType();
1501 CharUnits ElemTypeSize;
1502 if (ElemType->isVoidType() || ElemType->isFunctionType())
1503 ElemTypeSize = CharUnits::One();
1504 else
1505 ElemTypeSize = Ctx.getASTContext().getTypeSizeInChars(ElemType);
1506
1507 PrimType IntT = classifyPrim(E->getType());
1508 if (!this->emitSubPtr(IntT, ElemTypeSize.getQuantity(), E))
1509 return false;
1510 return DiscardResult ? this->emitPop(IntT, E) : true;
1511 }
1512
1513 PrimType OffsetType;
1514 if (LHS->getType()->isIntegerType()) {
1515 if (!visitAsPointer(RHS, *RT))
1516 return false;
1517 if (!this->visit(LHS))
1518 return false;
1519 OffsetType = *LT;
1520 } else if (RHS->getType()->isIntegerType()) {
1521 if (!visitAsPointer(LHS, *LT))
1522 return false;
1523 if (!this->visit(RHS))
1524 return false;
1525 OffsetType = *RT;
1526 } else {
1527 return false;
1528 }
1529
1530 // Do the operation and optionally transform to
1531 // result pointer type.
1532 switch (Op) {
1533 case BO_Add:
1534 if (!this->emitAddOffset(OffsetType, E))
1535 return false;
1536 break;
1537 case BO_Sub:
1538 if (!this->emitSubOffset(OffsetType, E))
1539 return false;
1540 break;
1541 default:
1542 return false;
1543 }
1544
1545 PrimType ExprT = classifyPrim(E);
1546 if (ExprT != PT_Ptr) {
1547 if (!this->emitDecayPtr(PT_Ptr, ExprT, E))
1548 return false;
1549 }
1550
1551 if (DiscardResult)
1552 return this->emitPop(ExprT, E);
1553 return true;
1554}
1555
1556template <class Emitter>
1558 assert(E->isLogicalOp());
1559 BinaryOperatorKind Op = E->getOpcode();
1560 const Expr *LHS = E->getLHS();
1561 const Expr *RHS = E->getRHS();
1562
1563 if (Op == BO_LOr) {
1564 // Logical OR. Visit LHS and only evaluate RHS if LHS was FALSE.
1565 LabelTy LabelTrue = this->getLabel();
1566 LabelTy LabelEnd = this->getLabel();
1567
1568 if (!this->visitBool(LHS))
1569 return false;
1570 if (!this->jumpTrue(LabelTrue, E))
1571 return false;
1572
1573 if (!this->visitBool(RHS))
1574 return false;
1575 if (!this->jump(LabelEnd, E))
1576 return false;
1577
1578 this->emitLabel(LabelTrue);
1579 this->emitConstBool(true, E);
1580 this->fallthrough(LabelEnd);
1581 this->emitLabel(LabelEnd);
1582
1583 } else {
1584 assert(Op == BO_LAnd);
1585 // Logical AND.
1586 // Visit LHS. Only visit RHS if LHS was TRUE.
1587 LabelTy LabelFalse = this->getLabel();
1588 LabelTy LabelEnd = this->getLabel();
1589
1590 if (!this->visitBool(LHS))
1591 return false;
1592 if (!this->jumpFalse(LabelFalse, E))
1593 return false;
1594
1595 if (!this->visitBool(RHS))
1596 return false;
1597 if (!this->jump(LabelEnd, E))
1598 return false;
1599
1600 this->emitLabel(LabelFalse);
1601 this->emitConstBool(false, E);
1602 this->fallthrough(LabelEnd);
1603 this->emitLabel(LabelEnd);
1604 }
1605
1606 if (DiscardResult)
1607 return this->emitPopBool(E);
1608
1609 // For C, cast back to integer type.
1610 if (!E->getType()->isBooleanType()) {
1612 return this->emitCast(PT_Bool, T, E);
1613 }
1614 return true;
1615}
1616
1617template <class Emitter>
1619 // Prepare storage for result.
1620 if (!Initializing) {
1621 UnsignedOrNone LocalIndex = allocateTemporary(E);
1622 if (!LocalIndex)
1623 return false;
1624 if (!this->emitGetPtrLocal(*LocalIndex, E))
1625 return false;
1626 }
1627
1628 // Both LHS and RHS might _not_ be of complex type, but one of them
1629 // needs to be.
1630 const Expr *LHS = E->getLHS();
1631 const Expr *RHS = E->getRHS();
1632
1633 PrimType ResultElemT = this->classifyComplexElementType(E->getType());
1634 unsigned ResultOffset = ~0u;
1635 if (!DiscardResult)
1636 ResultOffset = this->allocateLocalPrimitive(E, PT_Ptr, /*IsConst=*/true);
1637
1638 // Save result pointer in ResultOffset
1639 if (!this->DiscardResult) {
1640 if (!this->emitDupPtr(E))
1641 return false;
1642 if (!this->emitSetLocal(PT_Ptr, ResultOffset, E))
1643 return false;
1644 }
1645 QualType LHSType = LHS->getType();
1646 if (const auto *AT = LHSType->getAs<AtomicType>())
1647 LHSType = AT->getValueType();
1648 QualType RHSType = RHS->getType();
1649 if (const auto *AT = RHSType->getAs<AtomicType>())
1650 RHSType = AT->getValueType();
1651
1652 bool LHSIsComplex = LHSType->isAnyComplexType();
1653 unsigned LHSOffset;
1654 bool RHSIsComplex = RHSType->isAnyComplexType();
1655
1656 // For ComplexComplex Mul, we have special ops to make their implementation
1657 // easier.
1658 BinaryOperatorKind Op = E->getOpcode();
1659 if (Op == BO_Mul && LHSIsComplex && RHSIsComplex) {
1660 assert(classifyPrim(LHSType->getAs<ComplexType>()->getElementType()) ==
1662 PrimType ElemT =
1664 if (!this->visit(LHS))
1665 return false;
1666 if (!this->visit(RHS))
1667 return false;
1668 if (!this->emitMulc(ElemT, E))
1669 return false;
1670 if (DiscardResult)
1671 return this->emitPopPtr(E);
1672 return true;
1673 }
1674
1675 if (Op == BO_Div && RHSIsComplex) {
1676 QualType ElemQT = RHSType->getAs<ComplexType>()->getElementType();
1677 PrimType ElemT = classifyPrim(ElemQT);
1678 // If the LHS is not complex, we still need to do the full complex
1679 // division, so just stub create a complex value and stub it out with
1680 // the LHS and a zero.
1681
1682 if (!LHSIsComplex) {
1683 // This is using the RHS type for the fake-complex LHS.
1684 UnsignedOrNone LocalIndex = allocateTemporary(RHS);
1685 if (!LocalIndex)
1686 return false;
1687 LHSOffset = *LocalIndex;
1688
1689 if (!this->emitGetPtrLocal(LHSOffset, E))
1690 return false;
1691
1692 if (!this->visit(LHS))
1693 return false;
1694 // real is LHS
1695 if (!this->emitInitElem(ElemT, 0, E))
1696 return false;
1697 // imag is zero
1698 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1699 return false;
1700 if (!this->emitInitElem(ElemT, 1, E))
1701 return false;
1702 } else {
1703 if (!this->visit(LHS))
1704 return false;
1705 }
1706
1707 if (!this->visit(RHS))
1708 return false;
1709 if (!this->emitDivc(ElemT, E))
1710 return false;
1711 if (DiscardResult)
1712 return this->emitPopPtr(E);
1713 return true;
1714 }
1715
1716 // Evaluate LHS and save value to LHSOffset.
1717 if (LHSType->isAnyComplexType()) {
1718 LHSOffset = this->allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true);
1719 if (!this->visit(LHS))
1720 return false;
1721 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
1722 return false;
1723 } else {
1724 PrimType LHST = classifyPrim(LHSType);
1725 LHSOffset = this->allocateLocalPrimitive(LHS, LHST, /*IsConst=*/true);
1726 if (!this->visit(LHS))
1727 return false;
1728 if (!this->emitSetLocal(LHST, LHSOffset, E))
1729 return false;
1730 }
1731
1732 // Same with RHS.
1733 unsigned RHSOffset;
1734 if (RHSType->isAnyComplexType()) {
1735 RHSOffset = this->allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true);
1736 if (!this->visit(RHS))
1737 return false;
1738 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
1739 return false;
1740 } else {
1741 PrimType RHST = classifyPrim(RHSType);
1742 RHSOffset = this->allocateLocalPrimitive(RHS, RHST, /*IsConst=*/true);
1743 if (!this->visit(RHS))
1744 return false;
1745 if (!this->emitSetLocal(RHST, RHSOffset, E))
1746 return false;
1747 }
1748
1749 // For both LHS and RHS, either load the value from the complex pointer, or
1750 // directly from the local variable. For index 1 (i.e. the imaginary part),
1751 // just load 0 and do the operation anyway.
1752 auto loadComplexValue = [this](bool IsComplex, bool LoadZero,
1753 unsigned ElemIndex, unsigned Offset,
1754 const Expr *E) -> bool {
1755 if (IsComplex) {
1756 if (!this->emitGetLocal(PT_Ptr, Offset, E))
1757 return false;
1758 return this->emitArrayElemPop(classifyComplexElementType(E->getType()),
1759 ElemIndex, E);
1760 }
1761 if (ElemIndex == 0 || !LoadZero)
1762 return this->emitGetLocal(classifyPrim(E->getType()), Offset, E);
1763 return this->visitZeroInitializer(classifyPrim(E->getType()), E->getType(),
1764 E);
1765 };
1766
1767 // Now we can get pointers to the LHS and RHS from the offsets above.
1768 for (unsigned ElemIndex = 0; ElemIndex != 2; ++ElemIndex) {
1769 // Result pointer for the store later.
1770 if (!this->DiscardResult) {
1771 if (!this->emitGetLocal(PT_Ptr, ResultOffset, E))
1772 return false;
1773 }
1774
1775 // The actual operation.
1776 switch (Op) {
1777 case BO_Add:
1778 if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS))
1779 return false;
1780
1781 if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS))
1782 return false;
1783 if (ResultElemT == PT_Float) {
1784 if (!this->emitAddf(getFPOptions(E), E))
1785 return false;
1786 } else {
1787 if (!this->emitAdd(ResultElemT, E))
1788 return false;
1789 }
1790 break;
1791 case BO_Sub:
1792 if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS))
1793 return false;
1794
1795 if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS))
1796 return false;
1797 if (ResultElemT == PT_Float) {
1798 if (!this->emitSubf(getFPOptions(E), E))
1799 return false;
1800 } else {
1801 if (!this->emitSub(ResultElemT, E))
1802 return false;
1803 }
1804 break;
1805 case BO_Mul:
1806 if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS))
1807 return false;
1808
1809 if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS))
1810 return false;
1811
1812 if (ResultElemT == PT_Float) {
1813 if (!this->emitMulf(getFPOptions(E), E))
1814 return false;
1815 } else {
1816 if (!this->emitMul(ResultElemT, E))
1817 return false;
1818 }
1819 break;
1820 case BO_Div:
1821 assert(!RHSIsComplex);
1822 if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS))
1823 return false;
1824
1825 if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS))
1826 return false;
1827
1828 if (ResultElemT == PT_Float) {
1829 if (!this->emitDivf(getFPOptions(E), E))
1830 return false;
1831 } else {
1832 if (!this->emitDiv(ResultElemT, E))
1833 return false;
1834 }
1835 break;
1836
1837 default:
1838 return false;
1839 }
1840
1841 if (!this->DiscardResult) {
1842 // Initialize array element with the value we just computed.
1843 if (!this->emitInitElemPop(ResultElemT, ElemIndex, E))
1844 return false;
1845 } else {
1846 if (!this->emitPop(ResultElemT, E))
1847 return false;
1848 // Remove the Complex temporary pointer we created ourselves at the
1849 // beginning of this function.
1850 if (!Initializing)
1851 return this->emitPopPtr(E);
1852 }
1853 }
1854 return true;
1855}
1856
1857template <class Emitter>
1859 const Expr *LHS = E->getLHS();
1860 const Expr *RHS = E->getRHS();
1861 assert(!E->isCommaOp() &&
1862 "Comma op should be handled in VisitBinaryOperator");
1863 assert(E->getType()->isVectorType());
1864 assert(LHS->getType()->isVectorType());
1865 assert(RHS->getType()->isVectorType());
1866
1867 // We can only handle vectors with primitive element types.
1869 return false;
1870
1871 // Prepare storage for result.
1872 if (!Initializing && !E->isCompoundAssignmentOp() && !E->isAssignmentOp()) {
1873 UnsignedOrNone LocalIndex = allocateTemporary(E);
1874 if (!LocalIndex)
1875 return false;
1876 if (!this->emitGetPtrLocal(*LocalIndex, E))
1877 return false;
1878 }
1879
1880 const auto *VecTy = E->getType()->getAs<VectorType>();
1881 auto Op = E->isCompoundAssignmentOp()
1883 : E->getOpcode();
1884
1885 PrimType ElemT = this->classifyVectorElementType(LHS->getType());
1886 PrimType RHSElemT = this->classifyVectorElementType(RHS->getType());
1887 PrimType ResultElemT = this->classifyVectorElementType(E->getType());
1888
1889 if (E->getOpcode() == BO_Assign) {
1890 assert(Ctx.getASTContext().hasSameUnqualifiedType(
1892 RHS->getType()->castAs<VectorType>()->getElementType()));
1893 if (!this->visit(LHS))
1894 return false;
1895 if (!this->visit(RHS))
1896 return false;
1897 if (!this->emitCopyArray(ElemT, 0, 0, VecTy->getNumElements(), E))
1898 return false;
1899 if (DiscardResult)
1900 return this->emitPopPtr(E);
1901 return true;
1902 }
1903
1904 // Evaluate LHS and save value to LHSOffset.
1905 unsigned LHSOffset =
1906 this->allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true);
1907 if (!this->visit(LHS))
1908 return false;
1909 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
1910 return false;
1911
1912 // Evaluate RHS and save value to RHSOffset.
1913 unsigned RHSOffset =
1914 this->allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true);
1915 if (!this->visit(RHS))
1916 return false;
1917 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
1918 return false;
1919
1920 if (E->isCompoundAssignmentOp() && !this->emitGetLocal(PT_Ptr, LHSOffset, E))
1921 return false;
1922
1923 // BitAdd/BitOr/BitXor/Shl/Shr doesn't support bool type, we need perform the
1924 // integer promotion.
1925 bool NeedIntPromot = ElemT == PT_Bool && (E->isBitwiseOp() || E->isShiftOp());
1926 QualType PromotTy;
1927 PrimType PromotT = PT_Bool;
1928 PrimType OpT = ElemT;
1929 if (NeedIntPromot) {
1930 PromotTy =
1931 Ctx.getASTContext().getPromotedIntegerType(Ctx.getASTContext().BoolTy);
1932 PromotT = classifyPrim(PromotTy);
1933 OpT = PromotT;
1934 }
1935
1936 auto getElem = [=](unsigned Offset, PrimType ElemT, unsigned Index) {
1937 if (!this->emitGetLocal(PT_Ptr, Offset, E))
1938 return false;
1939 if (!this->emitArrayElemPop(ElemT, Index, E))
1940 return false;
1941 if (E->isLogicalOp()) {
1942 if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
1943 return false;
1944 if (!this->emitPrimCast(PT_Bool, ResultElemT, VecTy->getElementType(), E))
1945 return false;
1946 } else if (NeedIntPromot) {
1947 if (!this->emitPrimCast(ElemT, PromotT, PromotTy, E))
1948 return false;
1949 }
1950 return true;
1951 };
1952
1953#define EMIT_ARITH_OP(OP) \
1954 { \
1955 if (ElemT == PT_Float) { \
1956 if (!this->emit##OP##f(getFPOptions(E), E)) \
1957 return false; \
1958 } else { \
1959 if (!this->emit##OP(ElemT, E)) \
1960 return false; \
1961 } \
1962 break; \
1963 }
1964
1965 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
1966 if (!getElem(LHSOffset, ElemT, I))
1967 return false;
1968 if (!getElem(RHSOffset, RHSElemT, I))
1969 return false;
1970 switch (Op) {
1971 case BO_Add:
1973 case BO_Sub:
1975 case BO_Mul:
1977 case BO_Div:
1979 case BO_Rem:
1980 if (!this->emitRem(ElemT, E))
1981 return false;
1982 break;
1983 case BO_And:
1984 if (!this->emitBitAnd(OpT, E))
1985 return false;
1986 break;
1987 case BO_Or:
1988 if (!this->emitBitOr(OpT, E))
1989 return false;
1990 break;
1991 case BO_Xor:
1992 if (!this->emitBitXor(OpT, E))
1993 return false;
1994 break;
1995 case BO_Shl:
1996 if (!this->emitShl(OpT, RHSElemT, E))
1997 return false;
1998 break;
1999 case BO_Shr:
2000 if (!this->emitShr(OpT, RHSElemT, E))
2001 return false;
2002 break;
2003 case BO_EQ:
2004 if (!this->emitEQ(ElemT, E))
2005 return false;
2006 break;
2007 case BO_NE:
2008 if (!this->emitNE(ElemT, E))
2009 return false;
2010 break;
2011 case BO_LE:
2012 if (!this->emitLE(ElemT, E))
2013 return false;
2014 break;
2015 case BO_LT:
2016 if (!this->emitLT(ElemT, E))
2017 return false;
2018 break;
2019 case BO_GE:
2020 if (!this->emitGE(ElemT, E))
2021 return false;
2022 break;
2023 case BO_GT:
2024 if (!this->emitGT(ElemT, E))
2025 return false;
2026 break;
2027 case BO_LAnd:
2028 // a && b is equivalent to a!=0 & b!=0
2029 if (!this->emitBitAnd(ResultElemT, E))
2030 return false;
2031 break;
2032 case BO_LOr:
2033 // a || b is equivalent to a!=0 | b!=0
2034 if (!this->emitBitOr(ResultElemT, E))
2035 return false;
2036 break;
2037 default:
2038 return this->emitInvalid(E);
2039 }
2040
2041 // The result of the comparison is a vector of the same width and number
2042 // of elements as the comparison operands with a signed integral element
2043 // type.
2044 //
2045 // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html
2046 if (E->isComparisonOp()) {
2047 if (!this->emitPrimCast(PT_Bool, ResultElemT, VecTy->getElementType(), E))
2048 return false;
2049 if (!this->emitNeg(ResultElemT, E))
2050 return false;
2051 }
2052
2053 // If we performed an integer promotion, we need to cast the compute result
2054 // into result vector element type.
2055 if (NeedIntPromot &&
2056 !this->emitPrimCast(PromotT, ResultElemT, VecTy->getElementType(), E))
2057 return false;
2058
2059 // Initialize array element with the value we just computed.
2060 if (!this->emitInitElem(ResultElemT, I, E))
2061 return false;
2062 }
2063
2064 if (DiscardResult && E->isCompoundAssignmentOp() && !this->emitPopPtr(E))
2065 return false;
2066 return true;
2067}
2068
2069template <class Emitter>
2071 const Expr *LHS = E->getLHS();
2072 const Expr *RHS = E->getRHS();
2073 const ASTContext &ASTCtx = Ctx.getASTContext();
2074
2075 assert(LHS->getType()->isFixedPointType() ||
2076 RHS->getType()->isFixedPointType());
2077
2078 auto LHSSema = ASTCtx.getFixedPointSemantics(LHS->getType());
2079 auto LHSSemaInt = LHSSema.toOpaqueInt();
2080 auto RHSSema = ASTCtx.getFixedPointSemantics(RHS->getType());
2081 auto RHSSemaInt = RHSSema.toOpaqueInt();
2082
2083 if (!this->visit(LHS))
2084 return false;
2085 if (!LHS->getType()->isFixedPointType()) {
2086 if (!this->emitCastIntegralFixedPoint(classifyPrim(LHS->getType()),
2087 LHSSemaInt, E))
2088 return false;
2089 }
2090
2091 if (!this->visit(RHS))
2092 return false;
2093 if (!RHS->getType()->isFixedPointType()) {
2094 if (!this->emitCastIntegralFixedPoint(classifyPrim(RHS->getType()),
2095 RHSSemaInt, E))
2096 return false;
2097 }
2098
2099 // Convert the result to the target semantics.
2100 auto ConvertResult = [&](bool R) -> bool {
2101 if (!R)
2102 return false;
2103 auto ResultSema = ASTCtx.getFixedPointSemantics(E->getType()).toOpaqueInt();
2104 auto CommonSema = LHSSema.getCommonSemantics(RHSSema).toOpaqueInt();
2105 if (ResultSema != CommonSema)
2106 return this->emitCastFixedPoint(ResultSema, E);
2107 return true;
2108 };
2109
2110 auto MaybeCastToBool = [&](bool Result) {
2111 if (!Result)
2112 return false;
2113 PrimType T = classifyPrim(E);
2114 if (DiscardResult)
2115 return this->emitPop(T, E);
2116 if (T != PT_Bool)
2117 return this->emitCast(PT_Bool, T, E);
2118 return true;
2119 };
2120
2121 switch (E->getOpcode()) {
2122 case BO_EQ:
2123 return MaybeCastToBool(this->emitEQFixedPoint(E));
2124 case BO_NE:
2125 return MaybeCastToBool(this->emitNEFixedPoint(E));
2126 case BO_LT:
2127 return MaybeCastToBool(this->emitLTFixedPoint(E));
2128 case BO_LE:
2129 return MaybeCastToBool(this->emitLEFixedPoint(E));
2130 case BO_GT:
2131 return MaybeCastToBool(this->emitGTFixedPoint(E));
2132 case BO_GE:
2133 return MaybeCastToBool(this->emitGEFixedPoint(E));
2134 case BO_Add:
2135 return ConvertResult(this->emitAddFixedPoint(E));
2136 case BO_Sub:
2137 return ConvertResult(this->emitSubFixedPoint(E));
2138 case BO_Mul:
2139 return ConvertResult(this->emitMulFixedPoint(E));
2140 case BO_Div:
2141 return ConvertResult(this->emitDivFixedPoint(E));
2142 case BO_Shl:
2143 return ConvertResult(this->emitShiftFixedPoint(/*Left=*/true, E));
2144 case BO_Shr:
2145 return ConvertResult(this->emitShiftFixedPoint(/*Left=*/false, E));
2146
2147 default:
2148 return this->emitInvalid(E);
2149 }
2150
2151 llvm_unreachable("unhandled binop opcode");
2152}
2153
2154template <class Emitter>
2156 const Expr *SubExpr = E->getSubExpr();
2157 assert(SubExpr->getType()->isFixedPointType());
2158
2159 switch (E->getOpcode()) {
2160 case UO_Plus:
2161 return this->delegate(SubExpr);
2162 case UO_Minus:
2163 if (!this->visit(SubExpr))
2164 return false;
2165 if (!this->emitNegFixedPoint(E))
2166 return false;
2167 if (DiscardResult)
2168 return this->emitPopFixedPoint(E);
2169 return true;
2170 default:
2171 return false;
2172 }
2173
2174 llvm_unreachable("Unhandled unary opcode");
2175}
2176
2177template <class Emitter>
2179 const ImplicitValueInitExpr *E) {
2180 if (DiscardResult)
2181 return true;
2182
2183 QualType QT = E->getType();
2184
2185 if (OptPrimType T = classify(QT))
2186 return this->visitZeroInitializer(*T, QT, E);
2187
2188 if (QT->isRecordType()) {
2189 const RecordDecl *RD = QT->getAsRecordDecl();
2190 assert(RD);
2191 if (RD->isInvalidDecl())
2192 return false;
2193
2194 const Record *R = getRecord(QT);
2195 if (!R)
2196 return false;
2197
2198 assert(Initializing);
2199 return this->visitZeroRecordInitializer(R, E);
2200 }
2201
2202 if (QT->isIncompleteArrayType())
2203 return true;
2204
2205 if (QT->isArrayType())
2206 return this->visitZeroArrayInitializer(QT, E);
2207
2208 if (const auto *ComplexTy = E->getType()->getAs<ComplexType>()) {
2209 assert(Initializing);
2210 QualType ElemQT = ComplexTy->getElementType();
2211 PrimType ElemT = classifyPrim(ElemQT);
2212 for (unsigned I = 0; I < 2; ++I) {
2213 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
2214 return false;
2215 if (!this->emitInitElem(ElemT, I, E))
2216 return false;
2217 }
2218 return true;
2219 }
2220
2221 if (const auto *VecT = E->getType()->getAs<VectorType>()) {
2222 unsigned NumVecElements = VecT->getNumElements();
2223 QualType ElemQT = VecT->getElementType();
2224 PrimType ElemT = classifyPrim(ElemQT);
2225
2226 for (unsigned I = 0; I < NumVecElements; ++I) {
2227 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
2228 return false;
2229 if (!this->emitInitElem(ElemT, I, E))
2230 return false;
2231 }
2232 return true;
2233 }
2234
2235 if (const auto *MT = E->getType()->getAs<ConstantMatrixType>()) {
2236 unsigned NumElems = MT->getNumElementsFlattened();
2237 QualType ElemQT = MT->getElementType();
2238 PrimType ElemT = classifyPrim(ElemQT);
2239
2240 for (unsigned I = 0; I != NumElems; ++I) {
2241 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
2242 return false;
2243 if (!this->emitInitElem(ElemT, I, E))
2244 return false;
2245 }
2246 return true;
2247 }
2248
2249 return false;
2250}
2251
2252template <class Emitter>
2254 if (E->getType()->isVoidType() || E->containsErrors())
2255 return false;
2256
2257 const Expr *LHS = E->getLHS();
2258 const Expr *RHS = E->getRHS();
2259 const Expr *Index = E->getIdx();
2260 const Expr *Base = E->getBase();
2261
2262 // C++17's rules require us to evaluate the LHS first, regardless of which
2263 // side is the base.
2264 bool Success = true;
2265 for (const Expr *SubExpr : {LHS, RHS}) {
2266 if (!this->visit(SubExpr)) {
2267 Success = false;
2268 continue;
2269 }
2270
2271 // Expand the base if this is a subscript on a
2272 // pointer expression.
2273 if (SubExpr == Base && Base->getType()->isPointerType()) {
2274 if (!this->emitExpandPtr(E))
2275 Success = false;
2276 }
2277 }
2278
2279 if (!Success)
2280 return false;
2281
2282 OptPrimType IndexT = classify(Index->getType());
2283 // In error-recovery cases, the index expression has a dependent type.
2284 if (!IndexT)
2285 return this->emitError(E);
2286 // If the index is first, we need to change that.
2287 if (LHS == Index) {
2288 if (!this->emitFlip(PT_Ptr, *IndexT, E))
2289 return false;
2290 }
2291
2292 if (!this->emitArrayElemPtrPop(*IndexT, E))
2293 return false;
2294 if (DiscardResult)
2295 return this->emitPopPtr(E);
2296
2297 if (E->isGLValue())
2298 return true;
2299
2301 return this->emitLoadPop(*T, E);
2302}
2303
2304template <class Emitter>
2306 const Expr *ArrayFiller, const Expr *E) {
2308
2309 QualType QT = E->getType();
2310 if (const auto *AT = QT->getAs<AtomicType>())
2311 QT = AT->getValueType();
2312
2313 if (QT->isVoidType()) {
2314 if (Inits.size() == 0)
2315 return true;
2316 return this->emitInvalid(E);
2317 }
2318
2319 // Handle discarding first.
2320 if (DiscardResult) {
2321 for (const Expr *Init : Inits) {
2322 if (!this->discard(Init))
2323 return false;
2324 }
2325 return true;
2326 }
2327
2328 // Primitive values.
2329 if (OptPrimType T = classify(QT)) {
2330 assert(!DiscardResult);
2331 if (Inits.size() == 0)
2332 return this->visitZeroInitializer(*T, QT, E);
2333 assert(Inits.size() == 1);
2334 return this->delegate(Inits[0]);
2335 }
2336
2337 if (QT->isRecordType()) {
2338 const Record *R = getRecord(QT);
2339
2340 if (Inits.size() == 1 && E->getType() == Inits[0]->getType())
2341 return this->delegate(Inits[0]);
2342
2343 if (!R)
2344 return false;
2345
2346 auto initPrimitiveField = [=](const Record::Field *FieldToInit,
2347 const Expr *Init, PrimType T,
2348 bool Activate = false) -> bool {
2350 if (!this->visit(Init))
2351 return false;
2352
2353 bool BitField = FieldToInit->isBitField();
2354 if (BitField && Activate)
2355 return this->emitInitBitFieldActivate(T, FieldToInit->Offset,
2356 FieldToInit->bitWidth(), E);
2357 if (BitField)
2358 return this->emitInitBitField(T, FieldToInit->Offset,
2359 FieldToInit->bitWidth(), E);
2360 if (Activate)
2361 return this->emitInitFieldActivate(T, FieldToInit->Offset, E);
2362 return this->emitInitField(T, FieldToInit->Offset, E);
2363 };
2364
2365 auto initCompositeField = [=](const Record::Field *FieldToInit,
2366 const Expr *Init,
2367 bool Activate = false) -> bool {
2369 InitLinkScope<Emitter> ILS(this, InitLink::Field(FieldToInit->Offset));
2370
2371 // Non-primitive case. Get a pointer to the field-to-initialize
2372 // on the stack and recurse into visitInitializer().
2373 if (!this->emitGetPtrField(FieldToInit->Offset, Init))
2374 return false;
2375
2376 if (Activate && !this->emitActivate(E))
2377 return false;
2378
2379 return this->visitInitializerPop(Init);
2380 };
2381
2382 if (R->isUnion()) {
2383 if (Inits.size() == 0) {
2384 if (!this->visitZeroRecordInitializer(R, E))
2385 return false;
2386 } else {
2387 const Expr *Init = Inits[0];
2388 const FieldDecl *FToInit = nullptr;
2389 if (const auto *ILE = dyn_cast<InitListExpr>(E))
2390 FToInit = ILE->getInitializedFieldInUnion();
2391 else
2392 FToInit = cast<CXXParenListInitExpr>(E)->getInitializedFieldInUnion();
2393
2394 const Record::Field *FieldToInit = R->getField(FToInit);
2395 if (OptPrimType T = classify(Init)) {
2396 if (!initPrimitiveField(FieldToInit, Init, *T, /*Activate=*/true))
2397 return false;
2398 } else {
2399 if (!initCompositeField(FieldToInit, Init, /*Activate=*/true))
2400 return false;
2401 }
2402 }
2403 return this->emitFinishInit(E);
2404 }
2405
2406 assert(!R->isUnion());
2407 for (unsigned BI = 0; BI != R->getNumBases(); ++BI) {
2408 const Expr *Init = Inits[BI];
2409 const Record::Base *B = R->getBase(BI);
2411 InitLinkScope<Emitter> ILS(this, InitLink::Base(B->Offset));
2412 if (!this->emitGetPtrBase(B->Offset, Init))
2413 return false;
2414 if (!this->visitInitializerPop(Init))
2415 return false;
2416 }
2417
2418 unsigned FieldIndex = 0;
2419 for (unsigned FI = R->getNumBases(); FI != Inits.size();) {
2420 const Record::Field *FieldToInit = R->getField(FieldIndex);
2421 if (FieldToInit->isUnnamedBitField()) {
2422 ++FieldIndex;
2423 continue;
2424 }
2425
2426 const Expr *Init = Inits[FI];
2427 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
2428 // aren't supposed to be modified.
2429 if (isa<NoInitExpr>(Init)) {
2430 ++FieldIndex;
2431 ++FI;
2432 continue;
2433 }
2434
2435 if (OptPrimType T = classify(Init)) {
2436 if (!initPrimitiveField(FieldToInit, Init, *T))
2437 return false;
2438 } else if (!initCompositeField(FieldToInit, Init)) {
2439 return false;
2440 }
2441
2442 ++FI;
2443 ++FieldIndex;
2444 }
2445
2446 assert(R->getNumVirtualBases() == 0);
2447
2448 return this->emitFinishInit(E);
2449 }
2450
2451 if (QT->isArrayType()) {
2452 const ConstantArrayType *CAT =
2453 Ctx.getASTContext().getAsConstantArrayType(QT);
2454 uint64_t NumElems = CAT->getZExtSize();
2455
2456 if (Initializing &&
2457 (!InitializingDecl || InitializingDecl->hasLocalStorage()) &&
2458 !this->emitCheckArrayDestSize(NumElems, E))
2459 return false;
2460
2461 if (Inits.size() == 1 && QT == Inits[0]->getType())
2462 return this->delegate(Inits[0]);
2463
2464 OptPrimType InitT = classify(CAT->getElementType());
2465 unsigned ElementIndex = 0;
2466 for (const Expr *Init : Inits) {
2467 if (const auto *EmbedS =
2468 dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
2469 PrimType TargetT = classifyPrim(Init->getType());
2470
2471 auto Eval = [&](const IntegerLiteral *IL, unsigned ElemIndex) {
2472 if (TargetT == PT_Float) {
2473 if (!this->emitConst(IL->getValue(), classifyPrim(IL), Init))
2474 return false;
2475 const auto *Sem = &Ctx.getFloatSemantics(CAT->getElementType());
2476 if (!this->emitCastIntegralFloating(classifyPrim(IL), Sem,
2477 getFPOptions(E), E))
2478 return false;
2479 } else {
2480 if (!this->emitConst(IL->getValue(), TargetT, Init))
2481 return false;
2482 }
2483 return this->emitInitElem(TargetT, ElemIndex, IL);
2484 };
2485 if (!EmbedS->doForEachDataElement(Eval, ElementIndex))
2486 return false;
2487 } else if (isa<NoInitExpr>(Init)) {
2488 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
2489 // aren't supposed to be modified.
2490 ++ElementIndex;
2491 } else {
2492 if (!this->visitArrayElemInit(ElementIndex, Init, InitT))
2493 return false;
2494 ++ElementIndex;
2495 }
2496 }
2497
2498 // Expand the filler expression.
2499 // FIXME: This should go away.
2500 if (ArrayFiller && !isa<NoInitExpr>(ArrayFiller)) {
2501 for (; ElementIndex != NumElems; ++ElementIndex) {
2502 if (!this->visitArrayElemInit(ElementIndex, ArrayFiller, InitT))
2503 return false;
2504 }
2505 }
2506
2507 return this->emitFinishInit(E);
2508 }
2509
2510 if (const auto *ComplexTy = QT->getAs<ComplexType>()) {
2511 unsigned NumInits = Inits.size();
2512
2513 if (NumInits == 1)
2514 return this->delegate(Inits[0]);
2515
2516 QualType ElemQT = ComplexTy->getElementType();
2517 PrimType ElemT = classifyPrim(ElemQT);
2518 if (NumInits == 0) {
2519 // Zero-initialize both elements.
2520 for (unsigned I = 0; I < 2; ++I) {
2521 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
2522 return false;
2523 if (!this->emitInitElem(ElemT, I, E))
2524 return false;
2525 }
2526 } else if (NumInits == 2) {
2527 unsigned InitIndex = 0;
2528 for (const Expr *Init : Inits) {
2529 if (!this->visit(Init))
2530 return false;
2531
2532 if (!this->emitInitElem(ElemT, InitIndex, E))
2533 return false;
2534 ++InitIndex;
2535 }
2536 }
2537 return true;
2538 }
2539
2540 if (const auto *VecT = QT->getAs<VectorType>()) {
2541 unsigned NumVecElements = VecT->getNumElements();
2542 assert(NumVecElements >= Inits.size());
2543
2544 QualType ElemQT = VecT->getElementType();
2545 PrimType ElemT = classifyPrim(ElemQT);
2546
2547 // All initializer elements.
2548 unsigned InitIndex = 0;
2549 for (const Expr *Init : Inits) {
2550 if (!this->visit(Init))
2551 return false;
2552
2553 // If the initializer is of vector type itself, we have to deconstruct
2554 // that and initialize all the target fields from the initializer fields.
2555 if (const auto *InitVecT = Init->getType()->getAs<VectorType>()) {
2556 if (!this->emitCopyArray(ElemT, 0, InitIndex,
2557 InitVecT->getNumElements(), E))
2558 return false;
2559 InitIndex += InitVecT->getNumElements();
2560 } else {
2561 if (!this->emitInitElem(ElemT, InitIndex, E))
2562 return false;
2563 ++InitIndex;
2564 }
2565 }
2566
2567 assert(InitIndex <= NumVecElements);
2568
2569 // Fill the rest with zeroes.
2570 for (; InitIndex != NumVecElements; ++InitIndex) {
2571 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
2572 return false;
2573 if (!this->emitInitElem(ElemT, InitIndex, E))
2574 return false;
2575 }
2576 return true;
2577 }
2578
2579 if (const auto *MT = QT->getAs<ConstantMatrixType>()) {
2580 unsigned NumElems = MT->getNumElementsFlattened();
2581 assert(Inits.size() == NumElems);
2582
2583 QualType ElemQT = MT->getElementType();
2584 PrimType ElemT = classifyPrim(ElemQT);
2585
2586 // Matrix initializer list elements are in row-major order, which matches
2587 // the matrix APValue convention and therefore no index remapping is
2588 // required.
2589 for (unsigned I = 0; I != NumElems; ++I) {
2590 if (!this->visit(Inits[I]))
2591 return false;
2592 if (!this->emitInitElem(ElemT, I, E))
2593 return false;
2594 }
2595 return true;
2596 }
2597
2598 return false;
2599}
2600
2601/// Pointer to the array(not the element!) must be on the stack when calling
2602/// this.
2603template <class Emitter>
2604bool Compiler<Emitter>::visitArrayElemInit(unsigned ElemIndex, const Expr *Init,
2605 OptPrimType InitT) {
2606 if (InitT) {
2607 // Visit the primitive element like normal.
2608 if (!this->visit(Init))
2609 return false;
2610 return this->emitInitElem(*InitT, ElemIndex, Init);
2611 }
2612
2613 InitLinkScope<Emitter> ILS(this, InitLink::Elem(ElemIndex));
2614 // Advance the pointer currently on the stack to the given
2615 // dimension.
2616 if (!this->emitConstUint32(ElemIndex, Init))
2617 return false;
2618 if (!this->emitArrayElemPtrUint32(Init))
2619 return false;
2620 return this->visitInitializerPop(Init);
2621}
2622
2623template <class Emitter>
2625 const FunctionDecl *FuncDecl,
2626 bool Activate, bool IsOperatorCall) {
2627 assert(VarScope->getKind() == ScopeKind::Call);
2628 llvm::BitVector NonNullArgs;
2629 if (FuncDecl && FuncDecl->hasAttr<NonNullAttr>())
2630 NonNullArgs = collectNonNullArgs(FuncDecl, Args);
2631
2632 bool ExplicitMemberFn = false;
2633 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl))
2634 ExplicitMemberFn = MD->isExplicitObjectMemberFunction();
2635
2636 unsigned ArgIndex = 0;
2637 for (const Expr *Arg : Args) {
2638 if (canClassify(Arg)) {
2639 if (!this->visit(Arg))
2640 return false;
2641 } else {
2642
2643 DeclOrExpr Source = Arg;
2644 if (FuncDecl) {
2645 // Try to use the parameter declaration instead of the argument
2646 // expression as a source.
2647 unsigned DeclIndex = ArgIndex - IsOperatorCall + ExplicitMemberFn;
2648 if (DeclIndex < FuncDecl->getNumParams())
2649 Source = FuncDecl->getParamDecl(ArgIndex - IsOperatorCall +
2650 ExplicitMemberFn);
2651 }
2652
2653 UnsignedOrNone LocalIndex =
2654 allocateLocal(std::move(Source), Arg->getType(), ScopeKind::Call);
2655 if (!LocalIndex)
2656 return false;
2657
2658 if (!this->emitGetPtrLocal(*LocalIndex, Arg))
2659 return false;
2660 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
2661 if (!this->visitInitializer(Arg))
2662 return false;
2663 }
2664
2665 if (ArgIndex == 1 && Activate) {
2666 if (!this->emitActivate(Arg))
2667 return false;
2668 }
2669
2670 if (!NonNullArgs.empty() && NonNullArgs[ArgIndex]) {
2671 PrimType ArgT = classify(Arg).value_or(PT_Ptr);
2672 if (ArgT == PT_Ptr) {
2673 if (!this->emitCheckNonNullArg(ArgT, Arg))
2674 return false;
2675 }
2676 }
2677
2678 ++ArgIndex;
2679 }
2680
2681 return true;
2682}
2683
2684template <class Emitter>
2686 return this->visitInitList(E->inits(), E->getArrayFiller(), E);
2687}
2688
2689template <class Emitter>
2694
2695template <class Emitter>
2700
2701template <class Emitter>
2703 if (!E->hasAPValueResult())
2704 return this->delegate(E->getSubExpr());
2705
2706 if (OptPrimType T = classify(E)) {
2707 // Try to emit the APValue directly, without visiting the subexpr.
2708 // This will only fail if we can't emit the APValue, so won't emit any
2709 // diagnostics or any double values.
2710 if (DiscardResult)
2711 return true;
2712 return this->visitAPValue(E->getAPValueResult(), *T, E);
2713 }
2714
2715 // Fall back to the subexpr for non-primitive APValues.
2716 return this->delegate(E->getSubExpr());
2717}
2718
2719template <class Emitter>
2721 auto It = E->begin();
2722 return this->visit(*It);
2723}
2724
2726 UnaryExprOrTypeTrait Kind) {
2727 bool AlignOfReturnsPreferred =
2728 ASTCtx.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver7);
2729
2730 // C++ [expr.alignof]p3:
2731 // When alignof is applied to a reference type, the result is the
2732 // alignment of the referenced type.
2733 if (const auto *Ref = T->getAs<ReferenceType>())
2734 T = Ref->getPointeeType();
2735
2736 if (T.getQualifiers().hasUnaligned())
2737 return CharUnits::One();
2738
2739 // __alignof is defined to return the preferred alignment.
2740 // Before 8, clang returned the preferred alignment for alignof and
2741 // _Alignof as well.
2742 if (Kind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
2743 return ASTCtx.toCharUnitsFromBits(ASTCtx.getPreferredTypeAlign(T));
2744
2745 return ASTCtx.getTypeAlignInChars(T);
2746}
2747
2748template <class Emitter>
2750 const UnaryExprOrTypeTraitExpr *E) {
2751
2752 UnaryExprOrTypeTrait Kind = E->getKind();
2753 const ASTContext &ASTCtx = Ctx.getASTContext();
2754
2755 if (Kind == UETT_SizeOf || Kind == UETT_DataSizeOf) {
2757
2758 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2759 // the result is the size of the referenced type."
2760 if (const auto *Ref = ArgType->getAs<ReferenceType>())
2761 ArgType = Ref->getPointeeType();
2762
2763 CharUnits Size;
2764 if (ArgType->isVoidType() || ArgType->isFunctionType())
2765 Size = CharUnits::One();
2766 else {
2767 if (ArgType->isDependentType() || !ArgType->isConstantSizeType())
2768 return this->emitInvalid(E);
2769
2770 if (Kind == UETT_SizeOf)
2771 Size = ASTCtx.getTypeSizeInChars(ArgType);
2772 else
2774 }
2775
2776 if (DiscardResult)
2777 return true;
2778
2779 return this->emitConst(Size.getQuantity(), E);
2780 }
2781
2782 if (Kind == UETT_CountOf) {
2783 QualType Ty = E->getTypeOfArgument();
2784 assert(Ty->isArrayType());
2785
2786 // We don't need to worry about array element qualifiers, so getting the
2787 // unsafe array type is fine.
2788 if (const auto *CAT =
2789 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
2790 if (DiscardResult)
2791 return true;
2792 return this->emitConst(CAT->getSize(), E);
2793 }
2794
2795 assert(!Ty->isConstantSizeType());
2796
2797 // If it's a variable-length array type, we need to check whether it is a
2798 // multidimensional array. If so, we need to check the size expression of
2799 // the VLA to see if it's a constant size. If so, we can return that value.
2800 const auto *VAT = ASTCtx.getAsVariableArrayType(Ty);
2801 assert(VAT);
2802 if (VAT->getElementType()->isArrayType()) {
2803 std::optional<APSInt> Res =
2804 VAT->getSizeExpr()
2805 ? VAT->getSizeExpr()->getIntegerConstantExpr(ASTCtx)
2806 : std::nullopt;
2807 if (Res) {
2808 if (DiscardResult)
2809 return true;
2810 return this->emitConst(*Res, E);
2811 }
2812 }
2813 }
2814
2815 if (Kind == UETT_AlignOf || Kind == UETT_PreferredAlignOf) {
2816 CharUnits Size;
2817
2818 if (E->isArgumentType()) {
2820
2821 Size = AlignOfType(ArgType, ASTCtx, Kind);
2822 } else {
2823 // Argument is an expression, not a type.
2824 const Expr *Arg = E->getArgumentExpr()->IgnoreParens();
2825
2826 if (Arg->getType()->isDependentType())
2827 return false;
2828
2829 // The kinds of expressions that we have special-case logic here for
2830 // should be kept up to date with the special checks for those
2831 // expressions in Sema.
2832
2833 // alignof decl is always accepted, even if it doesn't make sense: we
2834 // default to 1 in those cases.
2835 if (const auto *DRE = dyn_cast<DeclRefExpr>(Arg))
2836 Size = ASTCtx.getDeclAlign(DRE->getDecl(),
2837 /*RefAsPointee*/ true);
2838 else if (const auto *ME = dyn_cast<MemberExpr>(Arg))
2839 Size = ASTCtx.getDeclAlign(ME->getMemberDecl(),
2840 /*RefAsPointee*/ true);
2841 else
2842 Size = AlignOfType(Arg->getType(), ASTCtx, Kind);
2843 }
2844
2845 if (DiscardResult)
2846 return true;
2847
2848 return this->emitConst(Size.getQuantity(), E);
2849 }
2850
2851 if (Kind == UETT_VectorElements) {
2852 if (E->containsErrors())
2853 return false;
2854
2855 if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>())
2856 return this->emitConst(VT->getNumElements(), E);
2858 return this->emitSizelessVectorElementSize(E);
2859 }
2860
2861 if (Kind == UETT_VecStep) {
2862 if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>()) {
2863 unsigned N = VT->getNumElements();
2864
2865 // The vec_step built-in functions that take a 3-component
2866 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2867 if (N == 3)
2868 N = 4;
2869
2870 return this->emitConst(N, E);
2871 }
2872 return this->emitConst(1, E);
2873 }
2874
2875 if (Kind == UETT_OpenMPRequiredSimdAlign) {
2876 if (E->containsErrors())
2877 return false;
2878 assert(E->isArgumentType());
2879 unsigned Bits = ASTCtx.getOpenMPDefaultSimdAlign(E->getArgumentType());
2880
2881 return this->emitConst(ASTCtx.toCharUnitsFromBits(Bits).getQuantity(), E);
2882 }
2883
2884 if (Kind == UETT_PtrAuthTypeDiscriminator) {
2885 if (E->getArgumentType()->isDependentType())
2886 return this->emitInvalid(E);
2887
2888 return this->emitConst(
2889 const_cast<ASTContext &>(ASTCtx).getPointerAuthTypeDiscriminator(
2890 E->getArgumentType()),
2891 E);
2892 }
2893
2894 return false;
2895}
2896
2897template <class Emitter>
2899 // 'Base.Member'
2900 const Expr *Base = E->getBase();
2901 const ValueDecl *Member = E->getMemberDecl();
2902
2903 if (DiscardResult)
2904 return this->discard(Base);
2905
2906 if (const auto *VD = dyn_cast<VarDecl>(Member)) {
2907 // I am almost confident in saying that a var decl must be static
2908 // and therefore registered as a global variable.
2909 if (auto GlobalIndex = P.getGlobal(VD)) {
2910 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
2911 return false;
2912 if (Member->getType()->isReferenceType())
2913 return this->emitLoadPopPtr(E);
2914 return true;
2915 }
2916 return false;
2917 }
2918
2919 if (!isa<FieldDecl>(Member)) {
2920 // A non-static member function access only makes sense as part of the
2921 // enclosing call here. Don't try to evaluate it in isolation.
2922 if (const auto *MD = dyn_cast<CXXMethodDecl>(Member);
2923 MD && !MD->isStatic()) {
2924 return false;
2925 }
2926
2927 if (!this->discard(Base) && !this->emitSideEffect(E))
2928 return false;
2929
2930 return this->visitDeclRef(Member, E);
2931 }
2932
2933 if (!this->visit(Base))
2934 return false;
2935
2936 // Base above gives us a pointer on the stack.
2937 const auto *FD = cast<FieldDecl>(Member);
2938 const RecordDecl *RD = FD->getParent();
2939 const Record *R = getRecord(RD);
2940 if (!R)
2941 return false;
2942 const Record::Field *F = R->getField(FD);
2943
2944 // MemberExprs are almost always lvalues, in which case we don't need to
2945 // do the load. But sometimes they aren't.
2946 const auto maybeLoadValue = [&]() -> bool {
2947 if (E->isGLValue())
2948 return true;
2949 if (OptPrimType T = classify(E))
2950 return this->emitLoadPop(*T, E);
2951 return false;
2952 };
2953
2954 // Leave a pointer to the field on the stack.
2955 if (F->Decl->getType()->isReferenceType())
2956 return this->emitGetFieldPop(PT_Ptr, F->Offset, E) && maybeLoadValue();
2957 return this->emitGetPtrFieldPop(F->Offset, E) && maybeLoadValue();
2958}
2959
2960template <class Emitter>
2962 assert(!DiscardResult);
2963 // ArrayIndex might not be set if a ArrayInitIndexExpr is being evaluated
2964 // stand-alone, e.g. via EvaluateAsInt().
2965 if (!ArrayIndex)
2966 return false;
2967 return this->emitConst(*ArrayIndex, E);
2968}
2969
2970template <class Emitter>
2972 assert(Initializing);
2973 assert(!DiscardResult);
2974
2975 const Expr *Common = E->getCommonExpr();
2976 const Expr *SubExpr = E->getSubExpr();
2977 OptPrimType SubExprT = classify(SubExpr);
2978 size_t Size = E->getArraySize().getZExtValue();
2979
2980 if (SubExprT) {
2981 // Unwrap the OpaqueValueExpr so we don't cache something we won't reuse.
2982 Common = cast<OpaqueValueExpr>(Common)->getSourceExpr();
2983
2984 if (!this->visit(Common))
2985 return false;
2986 return this->emitCopyArray(*SubExprT, 0, 0, Size, E);
2987 }
2988
2989 // We visit the common opaque expression here once so we have its value
2990 // cached.
2991 if (!this->discard(Common))
2992 return false;
2993
2994 // TODO: This compiles to quite a lot of bytecode if the array is larger.
2995 // Investigate compiling this to a loop.
2996
2997 // So, every iteration, we execute an assignment here
2998 // where the LHS is on the stack (the target array)
2999 // and the RHS is our SubExpr.
3000 for (size_t I = 0; I != Size; ++I) {
3001 ArrayIndexScope<Emitter> IndexScope(this, I);
3003
3004 if (!this->visitArrayElemInit(I, SubExpr, SubExprT))
3005 return false;
3006 if (!BS.destroyLocals())
3007 return false;
3008 }
3009 return true;
3010}
3011
3012template <class Emitter>
3014 const Expr *SourceExpr = E->getSourceExpr();
3015 if (!SourceExpr)
3016 return false;
3017
3018 if (Initializing) {
3019 assert(!DiscardResult);
3020 return this->visitInitializer(SourceExpr);
3021 }
3022
3023 PrimType SubExprT = classify(SourceExpr).value_or(PT_Ptr);
3024 if (auto It = OpaqueExprs.find(E); It != OpaqueExprs.end()) {
3025 if (DiscardResult)
3026 return true;
3027 return this->emitGetLocal(SubExprT, It->second, E);
3028 }
3029
3030 if (!this->visit(SourceExpr))
3031 return false;
3032
3033 // At this point we either have the evaluated source expression or a pointer
3034 // to an object on the stack. We want to create a local variable that stores
3035 // this value.
3036 unsigned LocalIndex = allocateLocalPrimitive(E, SubExprT, /*IsConst=*/true);
3037 if (!this->emitSetLocal(SubExprT, LocalIndex, E))
3038 return false;
3039
3040 // This is cleaned up when the local variable is destroyed.
3041 OpaqueExprs.insert({E, LocalIndex});
3042
3043 // Here the local variable is created but the value is removed from the stack,
3044 // so we put it back if the caller needs it.
3045 if (!DiscardResult)
3046 return this->emitGetLocal(SubExprT, LocalIndex, E);
3047 return true;
3048}
3049
3050template <class Emitter>
3052 const AbstractConditionalOperator *E) {
3053 const Expr *Condition = E->getCond();
3054 const Expr *TrueExpr = E->getTrueExpr();
3055 const Expr *FalseExpr = E->getFalseExpr();
3056
3057 if (std::optional<bool> BoolValue = getBoolValue(Condition)) {
3058 if (*BoolValue)
3059 return this->delegate(TrueExpr);
3060 return this->delegate(FalseExpr);
3061 }
3062
3063 bool IsBcpCall = false;
3064 if (const auto *CE = dyn_cast<CallExpr>(Condition->IgnoreParenCasts());
3065 CE && CE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) {
3066 IsBcpCall = true;
3067 }
3068
3069 LabelTy LabelEnd = this->getLabel(); // Label after the operator.
3070 LabelTy LabelFalse = this->getLabel(); // Label for the false expr.
3071
3072 if (IsBcpCall) {
3073 if (!this->emitPushIgnoreDiags(E))
3074 return false;
3075 }
3076
3077 if (!this->visitBool(Condition)) {
3078 // If the condition failed and we're checking for undefined behavior
3079 // (which only happens with EvalEmitter) check the TrueExpr and FalseExpr
3080 // as well.
3081 if (this->checkingForUndefinedBehavior()) {
3082 if (!this->discard(TrueExpr))
3083 return false;
3084 if (!this->discard(FalseExpr))
3085 return false;
3086 }
3087 return false;
3088 }
3089
3090 // Force-init the scope, which creates a InitScope op. This is necessary so
3091 // the scope is not only initialized in one arm of the conditional operator.
3092 this->VarScope->forceInit();
3093 // The TrueExpr and FalseExpr of a conditional operator do _not_ create a
3094 // scope, which means the local variables created within them unconditionally
3095 // always exist. However, we need to later differentiate which branch was
3096 // taken and only destroy the varibles of the active branch. This is what the
3097 // "enabled" flags on local variables are used for.
3098 llvm::SaveAndRestore LAAA(this->VarScope->LocalsAlwaysEnabled,
3099 /*NewValue=*/false);
3100
3101 if (!this->jumpFalse(LabelFalse, E))
3102 return false;
3103 if (!this->delegate(TrueExpr))
3104 return false;
3105
3106 if (!this->jump(LabelEnd, E))
3107 return false;
3108 this->emitLabel(LabelFalse);
3109 if (!this->delegate(FalseExpr))
3110 return false;
3111
3112 this->fallthrough(LabelEnd);
3113 this->emitLabel(LabelEnd);
3114
3115 if (IsBcpCall)
3116 return this->emitPopIgnoreDiags(E);
3117 return true;
3118}
3119
3120template <class Emitter>
3122 if (DiscardResult)
3123 return true;
3124
3125 if (!Initializing)
3126 return this->emitGetStringPtr(E, E);
3127
3128 // We are initializing an array on the stack.
3129 const ConstantArrayType *CAT =
3130 Ctx.getASTContext().getAsConstantArrayType(E->getType());
3131 assert(CAT && "a string literal that's not a constant array?");
3132
3133 // If the initializer string is too long, a diagnostic has already been
3134 // emitted. Read only the array length from the string literal.
3135 unsigned ArraySize = CAT->getZExtSize();
3136 unsigned N = std::min(ArraySize, E->getLength());
3137 unsigned CharWidth = E->getCharByteWidth();
3138
3139 for (unsigned I = 0; I != N; ++I) {
3140 uint32_t CodeUnit = E->getCodeUnit(I);
3141
3142 if (CharWidth == 1) {
3143 this->emitConstSint8(CodeUnit, E);
3144 this->emitInitElemSint8(I, E);
3145 } else if (CharWidth == 2) {
3146 this->emitConstUint16(CodeUnit, E);
3147 this->emitInitElemUint16(I, E);
3148 } else if (CharWidth == 4) {
3149 this->emitConstUint32(CodeUnit, E);
3150 this->emitInitElemUint32(I, E);
3151 } else {
3152 llvm_unreachable("unsupported character width");
3153 }
3154 }
3155
3156 // Fill up the rest of the char array with NUL bytes.
3157 for (unsigned I = N; I != ArraySize; ++I) {
3158 if (CharWidth == 1) {
3159 this->emitConstSint8(0, E);
3160 this->emitInitElemSint8(I, E);
3161 } else if (CharWidth == 2) {
3162 this->emitConstUint16(0, E);
3163 this->emitInitElemUint16(I, E);
3164 } else if (CharWidth == 4) {
3165 this->emitConstUint32(0, E);
3166 this->emitInitElemUint32(I, E);
3167 } else {
3168 llvm_unreachable("unsupported character width");
3169 }
3170 }
3171
3172 return true;
3173}
3174
3175template <class Emitter>
3177 if (DiscardResult)
3178 return true;
3179 return this->emitDummyPtr(E, E);
3180}
3181
3182template <class Emitter>
3184 auto &A = Ctx.getASTContext();
3185 std::string Str;
3186 A.getObjCEncodingForType(E->getEncodedType(), Str);
3187 StringLiteral *SL =
3189 /*Pascal=*/false, E->getType(), E->getAtLoc());
3190 return this->delegate(SL);
3191}
3192
3193template <class Emitter>
3195 const SYCLUniqueStableNameExpr *E) {
3196 if (DiscardResult)
3197 return true;
3198
3199 assert(!Initializing);
3200
3201 auto &A = Ctx.getASTContext();
3202 std::string ResultStr = E->ComputeName(A);
3203
3204 QualType CharTy = A.CharTy.withConst();
3205 APInt Size(A.getTypeSize(A.getSizeType()), ResultStr.size() + 1);
3206 QualType ArrayTy = A.getConstantArrayType(CharTy, Size, nullptr,
3208
3209 StringLiteral *SL =
3211 /*Pascal=*/false, ArrayTy, E->getLocation());
3212 return this->emitGetStringPtr(SL, E);
3213}
3214
3215template <class Emitter>
3217 if (DiscardResult)
3218 return true;
3219 return this->emitConst(E->getValue(), E);
3220}
3221
3222template <class Emitter>
3224 const CompoundAssignOperator *E) {
3225
3226 const Expr *LHS = E->getLHS();
3227 const Expr *RHS = E->getRHS();
3228 QualType LHSType = LHS->getType();
3229 QualType LHSComputationType = E->getComputationLHSType();
3230 QualType ResultType = E->getComputationResultType();
3231 OptPrimType LT = classify(LHSComputationType);
3232 OptPrimType RT = classify(ResultType);
3233
3234 assert(ResultType->isFloatingType());
3235
3236 if (!LT || !RT)
3237 return false;
3238
3239 PrimType LHST = classifyPrim(LHSType);
3240
3241 if (isSideEffectFree(RHS)) {
3242 if (!visit(LHS))
3243 return false;
3244 if (!this->emitLoad(LHST, E))
3245 return false;
3246 // If necessary, convert LHS to its computation type.
3247 if (!this->emitPrimCast(LHST, classifyPrim(LHSComputationType),
3248 LHSComputationType, E))
3249 return false;
3250 if (!visit(RHS))
3251 return false;
3252
3253 } else {
3254 // C++17 onwards require that we evaluate the RHS first.
3255 // Compute RHS and save it in a temporary variable so we can
3256 // load it again later.
3257 if (!visit(RHS))
3258 return false;
3259
3260 unsigned TempOffset =
3261 this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true);
3262 if (!this->emitSetLocal(*RT, TempOffset, E))
3263 return false;
3264
3265 // First, visit LHS.
3266 if (!visit(LHS))
3267 return false;
3268 if (!this->emitLoad(LHST, E))
3269 return false;
3270
3271 // If necessary, convert LHS to its computation type.
3272 if (!this->emitPrimCast(LHST, classifyPrim(LHSComputationType),
3273 LHSComputationType, E))
3274 return false;
3275
3276 // Now load RHS.
3277 if (!this->emitGetLocal(*RT, TempOffset, E))
3278 return false;
3279 }
3280
3281 switch (E->getOpcode()) {
3282 case BO_AddAssign:
3283 if (!this->emitAddf(getFPOptions(E), E))
3284 return false;
3285 break;
3286 case BO_SubAssign:
3287 if (!this->emitSubf(getFPOptions(E), E))
3288 return false;
3289 break;
3290 case BO_MulAssign:
3291 if (!this->emitMulf(getFPOptions(E), E))
3292 return false;
3293 break;
3294 case BO_DivAssign:
3295 if (!this->emitDivf(getFPOptions(E), E))
3296 return false;
3297 break;
3298 default:
3299 return false;
3300 }
3301
3302 if (!this->emitPrimCast(classifyPrim(ResultType), LHST, LHS->getType(), E))
3303 return false;
3304
3305 if (DiscardResult)
3306 return this->emitStorePop(LHST, E);
3307 return this->emitStore(LHST, E);
3308}
3309
3310template <class Emitter>
3312 const CompoundAssignOperator *E) {
3313 BinaryOperatorKind Op = E->getOpcode();
3314 const Expr *LHS = E->getLHS();
3315 const Expr *RHS = E->getRHS();
3316 OptPrimType LT = classify(LHS->getType());
3317 OptPrimType RT = classify(RHS->getType());
3318
3319 if (Op != BO_AddAssign && Op != BO_SubAssign)
3320 return false;
3321
3322 if (!LT || !RT)
3323 return false;
3324
3325 if (!visit(LHS))
3326 return false;
3327
3328 if (!this->emitLoad(*LT, LHS))
3329 return false;
3330
3331 if (!visit(RHS))
3332 return false;
3333
3334 if (Op == BO_AddAssign) {
3335 if (!this->emitAddOffset(*RT, E))
3336 return false;
3337 } else {
3338 if (!this->emitSubOffset(*RT, E))
3339 return false;
3340 }
3341
3342 if (DiscardResult)
3343 return this->emitStorePopPtr(E);
3344 return this->emitStorePtr(E);
3345}
3346
3347template <class Emitter>
3349 const CompoundAssignOperator *E) {
3350 if (E->getType()->isVectorType())
3351 return VisitVectorBinOp(E);
3352
3353 const Expr *LHS = E->getLHS();
3354 const Expr *RHS = E->getRHS();
3355 OptPrimType LHSComputationT = classify(E->getComputationLHSType());
3356 OptPrimType LT = classify(LHS->getType());
3357 OptPrimType RT = classify(RHS->getType());
3358 OptPrimType ResultT = classify(E->getType());
3359
3360 if (!Ctx.getLangOpts().CPlusPlus14)
3361 return this->visit(RHS) && this->visit(LHS) && this->emitError(E);
3362
3363 if (!LT || !RT || !ResultT || !LHSComputationT)
3364 return false;
3365
3366 // Handle floating point operations separately here, since they
3367 // require special care.
3368 if (ResultT == PT_Float || RT == PT_Float)
3370
3371 if (E->getType()->isPointerType())
3373
3374 assert(!E->getType()->isPointerType() && "Handled above");
3375 assert(!E->getType()->isFloatingType() && "Handled above");
3376
3377 if (isSideEffectFree(RHS)) {
3378 if (!visit(LHS))
3379 return false;
3380 if (!this->emitLoad(*LT, E))
3381 return false;
3382 if (LT != LHSComputationT &&
3383 !this->emitIntegralCast(*LT, *LHSComputationT,
3384 E->getComputationLHSType(), E))
3385 return false;
3386 if (!visit(RHS))
3387 return false;
3388 } else {
3389 // C++17 onwards require that we evaluate the RHS first.
3390 // Compute RHS and save it in a temporary variable so we can
3391 // load it again later.
3392 // FIXME: Compound assignments are unsequenced in C, so we might
3393 // have to figure out how to reject them.
3394 if (!visit(RHS))
3395 return false;
3396
3397 unsigned TempOffset =
3398 this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true);
3399
3400 if (!this->emitSetLocal(*RT, TempOffset, E))
3401 return false;
3402
3403 // Get LHS pointer, load its value and cast it to the
3404 // computation type if necessary.
3405 if (!visit(LHS))
3406 return false;
3407 if (!this->emitLoad(*LT, E))
3408 return false;
3409 if (LT != LHSComputationT &&
3410 !this->emitIntegralCast(*LT, *LHSComputationT,
3411 E->getComputationLHSType(), E))
3412 return false;
3413
3414 // Get the RHS value on the stack.
3415 if (!this->emitGetLocal(*RT, TempOffset, E))
3416 return false;
3417 }
3418
3419 // Perform operation.
3420 switch (E->getOpcode()) {
3421 case BO_AddAssign:
3422 if (!this->emitAdd(*LHSComputationT, E))
3423 return false;
3424 break;
3425 case BO_SubAssign:
3426 if (!this->emitSub(*LHSComputationT, E))
3427 return false;
3428 break;
3429 case BO_MulAssign:
3430 if (!this->emitMul(*LHSComputationT, E))
3431 return false;
3432 break;
3433 case BO_DivAssign:
3434 if (!this->emitDiv(*LHSComputationT, E))
3435 return false;
3436 break;
3437 case BO_RemAssign:
3438 if (!this->emitRem(*LHSComputationT, E))
3439 return false;
3440 break;
3441 case BO_ShlAssign:
3442 if (!this->emitShl(*LHSComputationT, *RT, E))
3443 return false;
3444 break;
3445 case BO_ShrAssign:
3446 if (!this->emitShr(*LHSComputationT, *RT, E))
3447 return false;
3448 break;
3449 case BO_AndAssign:
3450 if (!this->emitBitAnd(*LHSComputationT, E))
3451 return false;
3452 break;
3453 case BO_XorAssign:
3454 if (!this->emitBitXor(*LHSComputationT, E))
3455 return false;
3456 break;
3457 case BO_OrAssign:
3458 if (!this->emitBitOr(*LHSComputationT, E))
3459 return false;
3460 break;
3461 default:
3462 llvm_unreachable("Unimplemented compound assign operator");
3463 }
3464
3465 // And now cast from LHSComputationT to ResultT.
3466 if (ResultT != LHSComputationT &&
3467 !this->emitIntegralCast(*LHSComputationT, *ResultT, E->getType(), E))
3468 return false;
3469
3470 // And store the result in LHS.
3471 if (DiscardResult) {
3472 if (LHS->refersToBitField())
3473 return this->emitStoreBitFieldPop(*ResultT, E);
3474 return this->emitStorePop(*ResultT, E);
3475 }
3476 if (LHS->refersToBitField())
3477 return this->emitStoreBitField(*ResultT, E);
3478 return this->emitStore(*ResultT, E);
3479}
3480
3481template <class Emitter>
3484 const Expr *SubExpr = E->getSubExpr();
3485
3486 return this->delegate(SubExpr) && ES.destroyLocals(E);
3487}
3488
3489template <class Emitter>
3491 const MaterializeTemporaryExpr *E) {
3492 if (Initializing) {
3493 // We already have a value, just initialize that.
3494 return this->delegate(E->getSubExpr());
3495 }
3496 // If we don't end up using the materialized temporary anyway, don't
3497 // bother creating it.
3498 if (DiscardResult)
3499 return this->discard(E->getSubExpr());
3500
3503 const Expr *Inner;
3504 if (!Ctx.getLangOpts().CPlusPlus11)
3505 Inner =
3506 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
3507 else
3508 Inner = E->getSubExpr();
3509
3510 // If we passed any comma operators, evaluate their LHSs.
3511 for (const Expr *LHS : CommaLHSs) {
3512 if (!this->discard(LHS))
3513 return false;
3514 }
3515
3516 // FIXME: Find a test case where Adjustments matters.
3517
3518 // When we're extending a global variable *or* the storage duration of
3519 // the temporary is explicitly static, create a global variable.
3520 OptPrimType InnerT = classify(Inner);
3521 const ValueDecl *ExtendingDecl = E->getExtendingDecl();
3522 bool IsStatic = E->getStorageDuration() == SD_Static;
3523 if (IsStatic ||
3524 (ExtendingDecl && Context::shouldBeGloballyIndexed(ExtendingDecl))) {
3525 UnsignedOrNone GlobalIndex = P.createGlobal(E, Inner->getType());
3526 if (!GlobalIndex)
3527 return false;
3528
3529 const LifetimeExtendedTemporaryDecl *TempDecl =
3531
3532 if (InnerT) {
3533 if (!this->visit(Inner))
3534 return false;
3535
3536 if (IsStatic) {
3537 assert(TempDecl);
3538 if (!this->emitInitGlobalTemp(*InnerT, *GlobalIndex, TempDecl, E))
3539 return false;
3540 } else {
3541 if (!this->emitInitGlobal(*InnerT, *GlobalIndex, E))
3542 return false;
3543 }
3544 return this->emitGetPtrGlobal(*GlobalIndex, E);
3545 }
3546
3547 if (!this->checkLiteralType(Inner))
3548 return false;
3549 // Non-primitive values.
3550 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
3551 return false;
3552 if (!this->visitInitializer(Inner))
3553 return false;
3554 if (IsStatic) {
3555 assert(TempDecl);
3556 return this->emitInitGlobalTempComp(TempDecl, E);
3557 }
3558 return true;
3559 }
3560
3564
3565 // For everyhing else, use local variables.
3566 if (InnerT) {
3567 bool IsConst = Inner->getType().isConstQualified();
3568 bool IsVolatile = Inner->getType().isVolatileQualified();
3569 unsigned LocalIndex =
3570 allocateLocalPrimitive(E, *InnerT, IsConst, IsVolatile, VarScope);
3571 if (!this->VarScope->LocalsAlwaysEnabled &&
3572 !this->emitEnableLocal(LocalIndex, E))
3573 return false;
3574
3575 if (!this->visit(Inner))
3576 return false;
3577 if (!this->emitSetLocal(*InnerT, LocalIndex, E))
3578 return false;
3579
3580 return this->emitGetPtrLocal(LocalIndex, E);
3581 }
3582
3583 if (!this->checkLiteralType(Inner))
3584 return false;
3585
3586 if (UnsignedOrNone LocalIndex =
3587 allocateLocal(E, Inner->getType(), VarScope)) {
3588 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
3589
3590 if (!this->VarScope->LocalsAlwaysEnabled &&
3591 !this->emitEnableLocal(*LocalIndex, E))
3592 return false;
3593
3594 if (!this->emitGetPtrLocal(*LocalIndex, E))
3595 return false;
3596 return this->visitInitializer(Inner);
3597 }
3598 return false;
3599}
3600
3601template <class Emitter>
3603 const CXXBindTemporaryExpr *E) {
3604 const Expr *SubExpr = E->getSubExpr();
3605
3606 if (Initializing)
3607 return this->delegate(SubExpr);
3608
3609 // Make sure we create a temporary even if we're discarding, since that will
3610 // make sure we will also call the destructor.
3611
3612 if (!this->visit(SubExpr))
3613 return false;
3614
3615 if (DiscardResult)
3616 return this->emitPopPtr(E);
3617 return true;
3618}
3619
3620template <class Emitter>
3622 const Expr *Init = E->getInitializer();
3623 if (DiscardResult)
3624 return this->discard(Init);
3625
3626 if (Initializing) {
3627 // We already have a value, just initialize that.
3628 return this->visitInitializer(Init);
3629 }
3630
3631 OptPrimType T = classify(E->getType());
3632 if (E->isFileScope()) {
3633 // Avoid creating a variable if this is a primitive RValue anyway.
3634 if (T && !E->isLValue())
3635 return this->delegate(Init);
3636
3637 UnsignedOrNone GlobalIndex = P.createGlobal(E, E->getType());
3638 if (!GlobalIndex)
3639 return false;
3640
3641 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
3642 return false;
3643
3644 // Since this is a global variable, we might've already seen,
3645 // don't do it again.
3646 if (P.isGlobalInitialized(*GlobalIndex))
3647 return true;
3648
3649 if (T) {
3650 if (!this->visit(Init))
3651 return false;
3652 return this->emitInitGlobal(*T, *GlobalIndex, E);
3653 }
3654
3655 return this->visitInitializer(Init);
3656 }
3657
3658 // Otherwise, use a local variable.
3659 if (T && !E->isLValue()) {
3660 // For primitive types, we just visit the initializer.
3661 return this->delegate(Init);
3662 }
3663
3664 unsigned LocalIndex;
3665 if (T)
3666 LocalIndex = this->allocateLocalPrimitive(Init, *T, /*IsConst=*/false);
3667 else if (UnsignedOrNone MaybeIndex = this->allocateLocal(Init))
3668 LocalIndex = *MaybeIndex;
3669 else
3670 return false;
3671
3672 if (!this->emitGetPtrLocal(LocalIndex, E))
3673 return false;
3674
3675 if (T)
3676 return this->visit(Init) && this->emitInit(*T, E);
3677 return this->visitInitializer(Init);
3678}
3679
3680template <class Emitter>
3682 if (DiscardResult)
3683 return true;
3684 if (E->isStoredAsBoolean()) {
3685 if (E->getType()->isBooleanType())
3686 return this->emitConstBool(E->getBoolValue(), E);
3687 return this->emitConst(E->getBoolValue(), E);
3688 }
3689 if (E->isStoredAsComparisonResult()) {
3690 const ComparisonCategoryInfo &CmpInfo =
3691 Ctx.getASTContext().CompCategories.getInfoForType(E->getType());
3692 const auto Result =
3693 ComparisonCategoryResult(E->getAPValue().getInt().getZExtValue());
3694 const Record *R = getRecord(E->getType());
3695 if (!R || R->getNumFields() == 0)
3696 return false;
3697 const Record::Field *Field = R->getField(0U);
3698 PrimType FieldT = classifyPrim(Field->Decl->getType());
3699 if (!this->emitConst(CmpInfo.getValueInfo(Result)->getIntValue(), FieldT,
3700 E))
3701 return false;
3702 return this->emitInitField(FieldT, Field->Offset, E);
3703 }
3704
3706 return this->visitAPValue(E->getAPValue(), T, E);
3707}
3708
3709template <class Emitter>
3711 if (DiscardResult)
3712 return true;
3713 return this->emitConst(E->getValue(), E);
3714}
3715
3716template <class Emitter>
3718 if (DiscardResult)
3719 return true;
3720
3721 assert(Initializing);
3722 const Record *R = P.getOrCreateRecord(E->getLambdaClass());
3723 if (!R)
3724 return false;
3725
3726 auto *CaptureInitIt = E->capture_init_begin();
3727 // Initialize all fields (which represent lambda captures) of the
3728 // record with their initializers.
3729 for (const Record::Field &F : R->fields()) {
3730 const Expr *Init = *CaptureInitIt;
3731 if (!Init || Init->containsErrors())
3732 continue;
3733 ++CaptureInitIt;
3734
3735 if (OptPrimType T = classify(Init)) {
3736 if (!this->visit(Init))
3737 return false;
3738
3739 if (!this->emitInitField(*T, F.Offset, E))
3740 return false;
3741 } else {
3742 if (!this->emitGetPtrField(F.Offset, E))
3743 return false;
3744
3745 if (!this->visitInitializerPop(Init))
3746 return false;
3747 }
3748 }
3749
3750 return true;
3751}
3752
3753template <class Emitter>
3755 if (DiscardResult)
3756 return true;
3757
3758 if (!Initializing)
3759 return this->emitGetStringPtr(E, E);
3760 return this->delegate(E->getFunctionName());
3761}
3762
3763template <class Emitter>
3765 if (E->getSubExpr() && !this->discard(E->getSubExpr()))
3766 return false;
3767
3768 return this->emitInvalid(E);
3769}
3770
3771template <class Emitter>
3773 const CXXReinterpretCastExpr *E) {
3774 const Expr *SubExpr = E->getSubExpr();
3775
3776 OptPrimType FromT = classify(SubExpr);
3777 OptPrimType ToT = classify(E);
3778
3779 if (!FromT || !ToT)
3780 return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, E);
3781
3782 if (FromT == PT_Ptr || ToT == PT_Ptr) {
3785 if (!this->emitInvalidCast(CastKind, /*Fatal=*/false, E))
3786 return false;
3787 if (E->getCastKind() == CK_LValueBitCast)
3788 return this->delegate(SubExpr);
3789 return this->VisitCastExpr(E);
3790 }
3791
3792 // Try to actually do the cast.
3793 bool Fatal = (ToT != FromT);
3794 if (!this->emitInvalidCast(CastKind::Reinterpret, Fatal, E))
3795 return false;
3796
3797 return this->VisitCastExpr(E);
3798}
3799
3800template <class Emitter>
3802 if (!Ctx.getLangOpts().CPlusPlus20) {
3803 if (!this->emitInvalidCast(CastKind::Dynamic, /*Fatal=*/false, E))
3804 return false;
3805 }
3806
3807 if (E->getCastKind() != CK_Dynamic)
3808 return this->VisitCastExpr(E);
3809
3810 QualType DestType = E->getType();
3811 // "target type must be a reference or pointer type to a defined class"
3812 if (DestType->isRecordType()) {
3813 assert(E->isGLValue());
3814 } else {
3815 assert(DestType->isPointerOrReferenceType());
3816 assert(DestType->isVoidPointerType() ||
3817 DestType->getPointeeType()->isRecordType());
3818 DestType = DestType->getPointeeType();
3819 }
3820
3821 if (!this->visit(E->getSubExpr()))
3822 return false;
3823 if (!this->emitDynamicCast(DestType.getTypePtr(),
3824 /*IsReferenceCast=*/E->isGLValue(), E))
3825 return false;
3826
3827 if (DiscardResult)
3828 return this->emitPopPtr(E);
3829 return true;
3830}
3831
3832template <class Emitter>
3834 assert(E->getType()->isBooleanType());
3835
3836 if (DiscardResult)
3837 return true;
3838 return this->emitConstBool(E->getValue(), E);
3839}
3840
3841template <class Emitter>
3843 QualType T = E->getType();
3844 assert(!canClassify(T));
3845
3846 if (T->isRecordType()) {
3847 const CXXConstructorDecl *Ctor = E->getConstructor();
3848
3849 // If we're discarding a construct expression, we still need
3850 // to allocate a variable and call the constructor and destructor.
3851 if (DiscardResult) {
3852 if (Ctor->isTrivial())
3853 return true;
3854 assert(!Initializing);
3855 UnsignedOrNone LocalIndex = allocateLocal(E);
3856
3857 if (!LocalIndex)
3858 return false;
3859
3860 if (!this->emitGetPtrLocal(*LocalIndex, E))
3861 return false;
3862 }
3863
3864 // Trivial copy/move constructor. Avoid copy.
3865 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
3866 Ctor->isTrivial() &&
3867 E->getArg(0)->isTemporaryObject(Ctx.getASTContext(),
3868 T->getAsCXXRecordDecl()))
3869 return this->visitInitializer(E->getArg(0));
3870
3871 // Zero initialization.
3872 bool ZeroInit = E->requiresZeroInitialization();
3873 if (ZeroInit) {
3874 const Record *R = getRecord(E->getType());
3875 if (!R)
3876 return false;
3877
3878 if (!this->visitZeroRecordInitializer(R, E))
3879 return false;
3880
3881 // If the constructor is trivial anyway, we're done.
3882 if (Ctor->isTrivial())
3883 return true;
3884 }
3885
3886 // Avoid materializing a temporary for an elidable copy/move constructor.
3887 if (!ZeroInit && E->isElidable()) {
3888 const Expr *SrcObj = E->getArg(0);
3889 assert(SrcObj->isTemporaryObject(Ctx.getASTContext(), Ctor->getParent()));
3890 assert(Ctx.getASTContext().hasSameUnqualifiedType(E->getType(),
3891 SrcObj->getType()));
3892 if (const auto *ME = dyn_cast<MaterializeTemporaryExpr>(SrcObj)) {
3893 if (!this->emitCheckFunctionDecl(Ctor, E))
3894 return false;
3895 return this->visitInitializer(ME->getSubExpr());
3896 }
3897 }
3898
3899 const Function *Func = getFunction(Ctor);
3900
3901 if (!Func)
3902 return false;
3903
3904 assert(Func->hasThisPointer());
3905 assert(!Func->hasRVO());
3906
3907 // The This pointer is already on the stack because this is an initializer,
3908 // but we need to dup() so the call() below has its own copy.
3909 if (!this->emitDupPtr(E))
3910 return false;
3911
3912 // Constructor arguments.
3913 for (const auto *Arg : E->arguments()) {
3914 if (!this->visit(Arg))
3915 return false;
3916 }
3917
3918 if (Func->isVariadic()) {
3919 uint32_t VarArgSize = 0;
3920 unsigned NumParams = Func->getNumWrittenParams();
3921 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I) {
3922 VarArgSize +=
3923 align(primSize(classify(E->getArg(I)->getType()).value_or(PT_Ptr)));
3924 }
3925 if (!this->emitCallVar(Func, VarArgSize, E))
3926 return false;
3927 } else {
3928 if (!this->emitCall(Func, 0, E)) {
3929 // When discarding, we don't need the result anyway, so clean up
3930 // the instance dup we did earlier in case surrounding code wants
3931 // to keep evaluating.
3932 if (DiscardResult)
3933 (void)this->emitPopPtr(E);
3934 return false;
3935 }
3936 }
3937
3938 if (DiscardResult)
3939 return this->emitPopPtr(E);
3940 return true;
3941 }
3942
3943 if (T->isArrayType()) {
3944 const Function *Func = getFunction(E->getConstructor());
3945 if (!Func)
3946 return false;
3947
3948 if (!this->emitDupPtr(E))
3949 return false;
3950
3951 std::function<bool(QualType)> initArrayDimension;
3952 initArrayDimension = [&](QualType T) -> bool {
3953 if (!T->isArrayType()) {
3954 // Constructor arguments.
3955 for (const auto *Arg : E->arguments()) {
3956 if (!this->visit(Arg))
3957 return false;
3958 }
3959
3960 return this->emitCall(Func, 0, E);
3961 }
3962
3963 const ConstantArrayType *CAT =
3964 Ctx.getASTContext().getAsConstantArrayType(T);
3965 if (!CAT)
3966 return false;
3967 QualType ElemTy = CAT->getElementType();
3968 unsigned NumElems = CAT->getZExtSize();
3969 for (size_t I = 0; I != NumElems; ++I) {
3970 if (!this->emitConstUint64(I, E))
3971 return false;
3972 if (!this->emitArrayElemPtrUint64(E))
3973 return false;
3974 if (!initArrayDimension(ElemTy))
3975 return false;
3976 }
3977 return this->emitPopPtr(E);
3978 };
3979
3980 return initArrayDimension(E->getType());
3981 }
3982
3983 return false;
3984}
3985
3986template <class Emitter>
3988 if (DiscardResult)
3989 return true;
3990
3991 const APValue Val =
3992 E->EvaluateInContext(Ctx.getASTContext(), SourceLocDefaultExpr);
3993
3994 // Things like __builtin_LINE().
3995 if (E->getType()->isIntegerType()) {
3996 assert(Val.isInt());
3997 const APSInt &I = Val.getInt();
3998 return this->emitConst(I, E);
3999 }
4000 // Otherwise, the APValue is an LValue, with only one element.
4001 // Theoretically, we don't need the APValue at all of course.
4002 assert(E->getType()->isPointerType());
4003 assert(Val.isLValue());
4004 const APValue::LValueBase &Base = Val.getLValueBase();
4005 if (const Expr *LValueExpr = Base.dyn_cast<const Expr *>())
4006 return this->visit(LValueExpr);
4007
4008 // Otherwise, we have a decl (which is the case for
4009 // __builtin_source_location).
4010 assert(Base.is<const ValueDecl *>());
4011 assert(Val.getLValuePath().size() == 0);
4012 const auto *BaseDecl = Base.dyn_cast<const ValueDecl *>();
4013 assert(BaseDecl);
4014
4015 auto *UGCD = cast<UnnamedGlobalConstantDecl>(BaseDecl);
4016
4017 UnsignedOrNone GlobalIndex = P.getOrCreateGlobal(UGCD);
4018 if (!GlobalIndex)
4019 return false;
4020
4021 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
4022 return false;
4023
4024 const Record *R = getRecord(E->getType());
4025 const APValue &V = UGCD->getValue();
4026 for (unsigned I = 0, N = R->getNumFields(); I != N; ++I) {
4027 const Record::Field *F = R->getField(I);
4028 const APValue &FieldValue = V.getStructField(I);
4029
4030 PrimType FieldT = classifyPrim(F->Decl->getType());
4031
4032 if (!this->visitAPValue(FieldValue, FieldT, E))
4033 return false;
4034 if (!this->emitInitField(FieldT, F->Offset, E))
4035 return false;
4036 }
4037
4038 // Leave the pointer to the global on the stack.
4039 return true;
4040}
4041
4042template <class Emitter>
4044 unsigned N = E->getNumComponents();
4045 if (N == 0)
4046 return false;
4047
4048 for (unsigned I = 0; I != N; ++I) {
4049 const OffsetOfNode &Node = E->getComponent(I);
4050 if (Node.getKind() == OffsetOfNode::Array) {
4051 const Expr *ArrayIndexExpr = E->getIndexExpr(Node.getArrayExprIndex());
4052 PrimType IndexT = classifyPrim(ArrayIndexExpr->getType());
4053
4054 if (DiscardResult) {
4055 if (!this->discard(ArrayIndexExpr))
4056 return false;
4057 continue;
4058 }
4059
4060 if (IndexT == PT_IntAP || IndexT == PT_IntAPS) {
4061 if (!this->visit(ArrayIndexExpr))
4062 return false;
4063 if (!this->emitCastAPToOffsetIndex(IndexT, E))
4064 return false;
4065 continue;
4066 }
4067 if (!this->visit(ArrayIndexExpr))
4068 return false;
4069 // Cast to Sint64.
4070 if (IndexT != PT_Sint64) {
4071 if (!this->emitCast(IndexT, PT_Sint64, E))
4072 return false;
4073 }
4074 }
4075 }
4076
4077 if (DiscardResult)
4078 return true;
4079
4081 return this->emitOffsetOf(T, E, E);
4082}
4083
4084template <class Emitter>
4086 const CXXScalarValueInitExpr *E) {
4087 QualType Ty = E->getType();
4088
4089 if (DiscardResult || Ty->isVoidType())
4090 return true;
4091
4092 if (OptPrimType T = classify(Ty))
4093 return this->visitZeroInitializer(*T, Ty, E);
4094
4095 if (Ty->isAnyComplexType() || Ty->isVectorType()) {
4096 if (!Initializing) {
4097 UnsignedOrNone LocalIndex = allocateLocal(E);
4098 if (!LocalIndex)
4099 return false;
4100 if (!this->emitGetPtrLocal(*LocalIndex, E))
4101 return false;
4102 }
4103
4104 QualType ElemQT;
4105 unsigned NumElems;
4106 if (const auto *CT = Ty->getAs<ComplexType>()) {
4107 NumElems = 2;
4108 ElemQT = CT->getElementType();
4109 } else {
4110 const auto *VT = Ty->castAs<VectorType>();
4111 NumElems = VT->getNumElements();
4112 ElemQT = VT->getElementType();
4113 }
4114
4115 PrimType ElemT = classifyPrim(ElemQT);
4116
4117 // Initialize all fields to 0.
4118 for (unsigned I = 0; I != NumElems; ++I) {
4119 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
4120 return false;
4121 if (!this->emitInitElem(ElemT, I, E))
4122 return false;
4123 }
4124 return true;
4125 }
4126
4127 return false;
4128}
4129
4130template <class Emitter>
4132 return this->emitConst(E->getPackLength(), E);
4133}
4134
4135template <class Emitter>
4140
4141template <class Emitter>
4143 return this->delegate(E->getChosenSubExpr());
4144}
4145
4146template <class Emitter>
4148 if (DiscardResult)
4149 return true;
4150
4151 return this->emitConst(E->getValue(), E);
4152}
4153
4154template <class Emitter>
4156 const CXXInheritedCtorInitExpr *E) {
4157 const CXXConstructorDecl *Ctor = E->getConstructor();
4158 assert(!Ctor->isTrivial() &&
4159 "Trivial CXXInheritedCtorInitExpr, implement. (possible?)");
4160 const Function *F = this->getFunction(Ctor);
4161 if (!F)
4162 return false;
4163 assert(!F->hasRVO());
4164 assert(F->hasThisPointer());
4165
4166 if (!this->emitDupPtr(SourceInfo{}))
4167 return false;
4168
4169 // Forward all arguments of the current function (which should be a
4170 // constructor itself) to the inherited ctor.
4171 // This is necessary because the calling code has pushed the pointer
4172 // of the correct base for us already, but the arguments need
4173 // to come after.
4174 unsigned ParamIndex = 0;
4175 for (const ParmVarDecl *PD : Ctor->parameters()) {
4176 PrimType PT = this->classify(PD->getType()).value_or(PT_Ptr);
4177
4178 if (!this->emitGetParam(PT, ParamIndex, E))
4179 return false;
4180 ++ParamIndex;
4181 }
4182
4183 return this->emitCall(F, 0, E);
4184}
4185
4186// FIXME: This function has become rather unwieldy, especially
4187// the part where we initialize an array allocation of dynamic size.
4188template <class Emitter>
4190 assert(classifyPrim(E->getType()) == PT_Ptr);
4191 const Expr *Init = E->getInitializer();
4192 QualType ElementType = E->getAllocatedType();
4193 OptPrimType ElemT = classify(ElementType);
4194 unsigned PlacementArgs = E->getNumPlacementArgs();
4195 const FunctionDecl *OperatorNew = E->getOperatorNew();
4196 const Expr *PlacementDest = nullptr;
4197 bool IsNoThrow = false;
4198
4199 if (E->containsErrors())
4200 return false;
4201
4202 if (PlacementArgs != 0) {
4203 // FIXME: There is no restriction on this, but it's not clear that any
4204 // other form makes any sense. We get here for cases such as:
4205 //
4206 // new (std::align_val_t{N}) X(int)
4207 //
4208 // (which should presumably be valid only if N is a multiple of
4209 // alignof(int), and in any case can't be deallocated unless N is
4210 // alignof(X) and X has new-extended alignment).
4211 if (PlacementArgs == 1) {
4212 const Expr *Arg1 = E->getPlacementArg(0);
4213 if (Arg1->getType()->isNothrowT()) {
4214 if (!this->discard(Arg1))
4215 return false;
4216 IsNoThrow = true;
4217 } else {
4218 // Invalid unless we have C++26 or are in a std:: function.
4219 if (!this->emitInvalidNewDeleteExpr(E, E))
4220 return false;
4221
4222 // If we have a placement-new destination, we'll later use that instead
4223 // of allocating.
4224 if (OperatorNew->isReservedGlobalPlacementOperator())
4225 PlacementDest = Arg1;
4226 }
4227 } else {
4228 // Always invalid.
4229 return this->emitInvalid(E);
4230 }
4231 } else if (!OperatorNew
4232 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation())
4233 return this->emitInvalidNewDeleteExpr(E, E);
4234
4235 const Descriptor *Desc;
4236 if (!PlacementDest) {
4237 if (ElemT) {
4238 if (E->isArray())
4239 Desc = nullptr; // We're not going to use it in this case.
4240 else
4241 Desc = P.createDescriptor(E, *ElemT);
4242 } else {
4243 Desc = P.createDescriptor(E, ElementType.getTypePtr(), /*IsConst=*/false,
4244 /*IsTemporary=*/false, /*IsMutable=*/false,
4245 /*IsVolatile=*/false, Init);
4246 }
4247 }
4248
4249 if (E->isArray()) {
4250 std::optional<const Expr *> ArraySizeExpr = E->getArraySize();
4251 if (!ArraySizeExpr)
4252 return false;
4253
4254 const Expr *Stripped = *ArraySizeExpr;
4255 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
4256 Stripped = ICE->getSubExpr())
4257 if (ICE->getCastKind() != CK_NoOp &&
4258 ICE->getCastKind() != CK_IntegralCast)
4259 break;
4260
4261 PrimType SizeT = classifyPrim(Stripped->getType());
4262
4263 // Save evaluated array size to a variable.
4264 unsigned ArrayLen =
4265 allocateLocalPrimitive(Stripped, SizeT, /*IsConst=*/false);
4266 if (!this->visit(Stripped))
4267 return false;
4268 if (!this->emitSetLocal(SizeT, ArrayLen, E))
4269 return false;
4270
4271 if (PlacementDest) {
4272 if (!this->visit(PlacementDest))
4273 return false;
4274 if (!this->emitGetLocal(SizeT, ArrayLen, E))
4275 return false;
4276 if (!this->emitCheckNewTypeMismatchArray(SizeT, E, E))
4277 return false;
4278 } else {
4279 if (!this->emitGetLocal(SizeT, ArrayLen, E))
4280 return false;
4281
4282 if (ElemT) {
4283 // N primitive elements.
4284 if (!this->emitAllocN(SizeT, *ElemT, E, IsNoThrow, E))
4285 return false;
4286 } else {
4287 // N Composite elements.
4288 if (!this->emitAllocCN(SizeT, Desc, IsNoThrow, E))
4289 return false;
4290 }
4291 }
4292
4293 if (Init) {
4294 QualType InitType = Init->getType();
4295 size_t StaticInitElems = 0;
4296 const Expr *DynamicInit = nullptr;
4297 OptPrimType ElemT;
4298
4299 if (const ConstantArrayType *CAT =
4300 Ctx.getASTContext().getAsConstantArrayType(InitType)) {
4301 StaticInitElems = CAT->getZExtSize();
4302 // Initialize the first S element from the initializer.
4303 if (!this->visitInitializer(Init))
4304 return false;
4305
4306 if (const auto *ILE = dyn_cast<InitListExpr>(Init)) {
4307 if (ILE->hasArrayFiller())
4308 DynamicInit = ILE->getArrayFiller();
4309 else if (StaticInitElems > 0 && isa<StringLiteral>(ILE->getInit(0)))
4310 ElemT = classifyPrim(CAT->getElementType());
4311 }
4312 }
4313
4314 // The initializer initializes a certain number of elements, S.
4315 // However, the complete number of elements, N, might be larger than that.
4316 // In this case, we need to get an initializer for the remaining elements.
4317 // There are three cases:
4318 // 1) For the form 'new Struct[n];', the initializer is a
4319 // CXXConstructExpr and its type is an IncompleteArrayType.
4320 // 2) For the form 'new Struct[n]{1,2,3}', the initializer is an
4321 // InitListExpr and the initializer for the remaining elements
4322 // is the array filler.
4323 // 3) StringLiterals don't have an array filler, so we need to zero
4324 // the remaining elements.
4325
4326 if (DynamicInit || ElemT || InitType->isIncompleteArrayType()) {
4327 const Function *CtorFunc = nullptr;
4328 if (const auto *CE = dyn_cast<CXXConstructExpr>(Init)) {
4329 CtorFunc = getFunction(CE->getConstructor());
4330 if (!CtorFunc)
4331 return false;
4332 } else if (!DynamicInit && !ElemT)
4333 DynamicInit = Init;
4334
4335 LabelTy EndLabel = this->getLabel();
4336 LabelTy StartLabel = this->getLabel();
4337
4338 // In the nothrow case, the alloc above might have returned nullptr.
4339 // Don't call any constructors that case.
4340 if (IsNoThrow) {
4341 if (!this->emitDupPtr(E))
4342 return false;
4343 if (!this->emitIsNonNullPtr(E))
4344 return false;
4345 if (!this->jumpFalse(EndLabel, E))
4346 return false;
4347 }
4348
4349 // Create loop variables.
4350 unsigned Iter =
4351 allocateLocalPrimitive(Stripped, SizeT, /*IsConst=*/false);
4352 if (!this->emitConst(StaticInitElems, SizeT, E))
4353 return false;
4354 if (!this->emitSetLocal(SizeT, Iter, E))
4355 return false;
4356
4357 this->fallthrough(StartLabel);
4358 this->emitLabel(StartLabel);
4359 // Condition. Iter < ArrayLen?
4360 if (!this->emitGetLocal(SizeT, Iter, E))
4361 return false;
4362 if (!this->emitGetLocal(SizeT, ArrayLen, E))
4363 return false;
4364 if (!this->emitLT(SizeT, E))
4365 return false;
4366 if (!this->jumpFalse(EndLabel, E))
4367 return false;
4368
4369 // Pointer to the allocated array is already on the stack.
4370 if (!this->emitGetLocal(SizeT, Iter, E))
4371 return false;
4372 if (!this->emitArrayElemPtr(SizeT, E))
4373 return false;
4374
4375 if (isa_and_nonnull<ImplicitValueInitExpr>(DynamicInit) &&
4376 DynamicInit->getType()->isArrayType()) {
4377 QualType ElemType =
4378 DynamicInit->getType()->getAsArrayTypeUnsafe()->getElementType();
4379 if (OptPrimType InitT = classify(ElemType)) {
4380 if (!this->visitZeroInitializer(*InitT, ElemType, E))
4381 return false;
4382 if (!this->emitStorePop(*InitT, E))
4383 return false;
4384 } else {
4385 assert(ElemType->isArrayType());
4386 if (!this->visitZeroArrayInitializer(ElemType, E))
4387 return false;
4388 }
4389 } else if (DynamicInit) {
4390 if (OptPrimType InitT = classify(DynamicInit)) {
4391 if (!this->visit(DynamicInit))
4392 return false;
4393 if (!this->emitStorePop(*InitT, E))
4394 return false;
4395 } else {
4396 if (!this->visitInitializerPop(DynamicInit))
4397 return false;
4398 }
4399 } else if (ElemT) {
4400 if (!this->visitZeroInitializer(
4401 *ElemT, InitType->getAsArrayTypeUnsafe()->getElementType(),
4402 Init))
4403 return false;
4404 if (!this->emitStorePop(*ElemT, E))
4405 return false;
4406 } else {
4407 assert(CtorFunc);
4408 if (!this->emitCall(CtorFunc, 0, E))
4409 return false;
4410 }
4411
4412 // ++Iter;
4413 if (!this->emitGetPtrLocal(Iter, E))
4414 return false;
4415 if (!this->emitIncPop(SizeT, false, E))
4416 return false;
4417
4418 if (!this->jump(StartLabel, E))
4419 return false;
4420
4421 this->fallthrough(EndLabel);
4422 this->emitLabel(EndLabel);
4423 }
4424 }
4425 } else { // Non-array.
4426 if (PlacementDest) {
4427 if (!this->visit(PlacementDest))
4428 return false;
4429 if (!this->emitCheckNewTypeMismatch(E, E))
4430 return false;
4431
4432 } else {
4433 // Allocate just one element.
4434 if (!this->emitAlloc(Desc, E))
4435 return false;
4436 }
4437
4438 if (Init) {
4439 if (ElemT) {
4440 if (!this->visit(Init))
4441 return false;
4442
4443 if (!this->emitInit(*ElemT, E))
4444 return false;
4445 } else {
4446 // Composite.
4447 if (!this->visitInitializer(Init))
4448 return false;
4449 }
4450 }
4451 }
4452
4453 if (DiscardResult)
4454 return this->emitPopPtr(E);
4455
4456 return true;
4457}
4458
4459template <class Emitter>
4461 if (E->containsErrors())
4462 return false;
4463 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
4464
4465 if (!OperatorDelete->isUsableAsGlobalAllocationFunctionInConstantEvaluation())
4466 return this->emitInvalidNewDeleteExpr(E, E);
4467
4468 // Arg must be an lvalue.
4469 if (!this->visit(E->getArgument()))
4470 return false;
4471
4472 return this->emitFree(E->isArrayForm(), E->isGlobalDelete(), E);
4473}
4474
4475template <class Emitter>
4477 if (DiscardResult)
4478 return true;
4479
4480 const Function *Func = nullptr;
4481 if (const Function *F = Ctx.getOrCreateObjCBlock(E))
4482 Func = F;
4483
4484 if (!Func)
4485 return false;
4486 return this->emitGetFnPtr(Func, E);
4487}
4488
4489template <class Emitter>
4491 const Type *TypeInfoType = E->getType().getTypePtr();
4492
4493 auto canonType = [](const Type *T) {
4494 return T->getCanonicalTypeUnqualified().getTypePtr();
4495 };
4496
4497 if (!E->isPotentiallyEvaluated()) {
4498 if (DiscardResult)
4499 return true;
4500
4501 if (E->isTypeOperand())
4502 return this->emitGetTypeid(
4503 canonType(E->getTypeOperand(Ctx.getASTContext()).getTypePtr()),
4504 TypeInfoType, E);
4505
4506 return this->emitGetTypeid(
4507 canonType(E->getExprOperand()->getType().getTypePtr()), TypeInfoType,
4508 E);
4509 }
4510
4511 // Otherwise, we need to evaluate the expression operand.
4512 assert(E->getExprOperand());
4513 assert(E->getExprOperand()->isLValue());
4514
4515 if (!Ctx.getLangOpts().CPlusPlus20 && !this->emitDiagTypeid(E))
4516 return false;
4517
4518 if (!this->visit(E->getExprOperand()))
4519 return false;
4520
4521 if (!this->emitGetTypeidPtr(TypeInfoType, E))
4522 return false;
4523 if (DiscardResult)
4524 return this->emitPopPtr(E);
4525 return true;
4526}
4527
4528template <class Emitter>
4530 const ObjCDictionaryLiteral *E) {
4532 return this->emitDummyPtr(E, E);
4533 return this->emitError(E);
4534}
4535
4536template <class Emitter>
4539 return this->emitDummyPtr(E, E);
4540 return this->emitError(E);
4541}
4542
4543template <class Emitter>
4545 assert(Ctx.getLangOpts().CPlusPlus);
4546 return this->emitConstBool(E->getValue(), E);
4547}
4548
4549template <class Emitter>
4551 if (DiscardResult)
4552 return true;
4553 assert(!Initializing);
4554
4555 const MSGuidDecl *GuidDecl = E->getGuidDecl();
4556 const RecordDecl *RD = GuidDecl->getType()->getAsRecordDecl();
4557 assert(RD);
4558 // If the definiton of the result type is incomplete, just return a dummy.
4559 // If (and when) that is read from, we will fail, but not now.
4560 if (!RD->isCompleteDefinition())
4561 return this->emitDummyPtr(GuidDecl, E);
4562
4563 UnsignedOrNone GlobalIndex = P.getOrCreateGlobal(GuidDecl);
4564 if (!GlobalIndex)
4565 return false;
4566 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
4567 return false;
4568
4569 assert(this->getRecord(E->getType()));
4570
4571 const APValue &V = GuidDecl->getAsAPValue();
4572 if (V.getKind() == APValue::None)
4573 return true;
4574
4575 assert(V.isStruct());
4576 assert(V.getStructNumBases() == 0);
4577 if (!this->visitAPValueInitializer(V, E, E->getType()))
4578 return false;
4579
4580 return this->emitFinishInit(E);
4581}
4582
4583template <class Emitter>
4585 assert(classifyPrim(E->getType()) == PT_Bool);
4586 if (E->isValueDependent())
4587 return false;
4588 if (DiscardResult)
4589 return true;
4590 return this->emitConstBool(E->isSatisfied(), E);
4591}
4592
4593template <class Emitter>
4595 const ConceptSpecializationExpr *E) {
4596 assert(classifyPrim(E->getType()) == PT_Bool);
4597 if (DiscardResult)
4598 return true;
4599 return this->emitConstBool(E->isSatisfied(), E);
4600}
4601
4602template <class Emitter>
4607
4608template <class Emitter>
4610
4611 for (const Expr *SemE : E->semantics()) {
4612 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
4613 if (SemE == E->getResultExpr())
4614 return false;
4615
4616 if (OVE->isUnique())
4617 continue;
4618
4619 if (!this->discard(OVE))
4620 return false;
4621 } else if (SemE == E->getResultExpr()) {
4622 if (!this->delegate(SemE))
4623 return false;
4624 } else {
4625 if (!this->discard(SemE))
4626 return false;
4627 }
4628 }
4629 return true;
4630}
4631
4632template <class Emitter>
4636
4637template <class Emitter>
4639 return this->emitError(E);
4640}
4641
4642template <class Emitter>
4644 assert(E->getType()->isVoidPointerType());
4645 if (DiscardResult)
4646 return true;
4647
4648 return this->emitDummyPtr(E, E);
4649}
4650
4651template <class Emitter>
4652bool Compiler<Emitter>::emitVectorConversion(const Expr *Src, const Expr *E) {
4653 if (Src->containsErrors())
4654 return false;
4655
4656 const auto *VT = E->getType()->castAs<VectorType>();
4657 QualType ElemType = VT->getElementType();
4658 PrimType ElemT = classifyPrim(ElemType);
4659 QualType SrcType = Src->getType();
4660 PrimType SrcElemT = classifyVectorElementType(SrcType);
4661
4662 if (!Initializing) {
4663 UnsignedOrNone LocalIndex = allocateLocal(E);
4664 if (!LocalIndex)
4665 return false;
4666 if (!this->emitGetPtrLocal(*LocalIndex, E))
4667 return false;
4668 }
4669
4670 unsigned SrcOffset =
4671 this->allocateLocalPrimitive(Src, PT_Ptr, /*IsConst=*/true);
4672 if (!this->visit(Src))
4673 return false;
4674 if (!this->emitSetLocal(PT_Ptr, SrcOffset, E))
4675 return false;
4676
4677 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
4678 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
4679 return false;
4680 if (!this->emitArrayElemPop(SrcElemT, I, E))
4681 return false;
4682
4683 // Cast to the desired result element type.
4684 if (SrcElemT != ElemT) {
4685 if (!this->emitPrimCast(SrcElemT, ElemT, ElemType, E))
4686 return false;
4687 } else if (ElemType->isFloatingType() && SrcType != ElemType) {
4688 const auto *TargetSemantics = &Ctx.getFloatSemantics(ElemType);
4689 if (!this->emitCastFP(TargetSemantics, getRoundingMode(E), E))
4690 return false;
4691 }
4692 if (!this->emitInitElem(ElemT, I, E))
4693 return false;
4694 }
4695 return true;
4696}
4697
4698template <class Emitter>
4700 return emitVectorConversion(E->getSrcExpr(), E);
4701}
4702
4703template <class Emitter>
4705 // FIXME: Unary shuffle with mask not currently supported.
4706 if (E->getNumSubExprs() == 2)
4707 return this->emitInvalid(E);
4708
4709 assert(E->getNumSubExprs() > 2);
4710
4711 const Expr *Vecs[] = {E->getExpr(0), E->getExpr(1)};
4712 const VectorType *VT = Vecs[0]->getType()->castAs<VectorType>();
4713 PrimType ElemT = classifyPrim(VT->getElementType());
4714 unsigned NumInputElems = VT->getNumElements();
4715 unsigned NumOutputElems = E->getNumSubExprs() - 2;
4716 assert(NumOutputElems > 0);
4717
4718 if (!Initializing) {
4719 UnsignedOrNone LocalIndex = allocateLocal(E);
4720 if (!LocalIndex)
4721 return false;
4722 if (!this->emitGetPtrLocal(*LocalIndex, E))
4723 return false;
4724 }
4725
4726 // Save both input vectors to a local variable.
4727 unsigned VectorOffsets[2];
4728 for (unsigned I = 0; I != 2; ++I) {
4729 VectorOffsets[I] =
4730 this->allocateLocalPrimitive(Vecs[I], PT_Ptr, /*IsConst=*/true);
4731 if (!this->visit(Vecs[I]))
4732 return false;
4733 if (!this->emitSetLocal(PT_Ptr, VectorOffsets[I], E))
4734 return false;
4735 }
4736 for (unsigned I = 0; I != NumOutputElems; ++I) {
4737 APSInt ShuffleIndex = E->getShuffleMaskIdx(I);
4738 assert(ShuffleIndex >= -1);
4739 if (ShuffleIndex == -1)
4740 return this->emitInvalidShuffleVectorIndex(I, E);
4741
4742 assert(ShuffleIndex < (NumInputElems * 2));
4743 if (!this->emitGetLocal(PT_Ptr,
4744 VectorOffsets[ShuffleIndex >= NumInputElems], E))
4745 return false;
4746 unsigned InputVectorIndex = ShuffleIndex.getZExtValue() % NumInputElems;
4747 if (!this->emitArrayElemPop(ElemT, InputVectorIndex, E))
4748 return false;
4749
4750 if (!this->emitInitElem(ElemT, I, E))
4751 return false;
4752 }
4753
4754 if (DiscardResult)
4755 return this->emitPopPtr(E);
4756
4757 return true;
4758}
4759
4760template <class Emitter>
4762 const ExtVectorElementExpr *E) {
4763 const Expr *Base = E->getBase();
4764 assert(
4765 Base->getType()->isVectorType() ||
4766 Base->getType()->getAs<PointerType>()->getPointeeType()->isVectorType());
4767
4769 E->getEncodedElementAccess(Indices);
4770
4771 if (Indices.size() == 1) {
4772 if (!this->visit(Base))
4773 return false;
4774
4775 if (E->isGLValue()) {
4776 if (!this->emitConstUint32(Indices[0], E))
4777 return false;
4778 return this->emitArrayElemPtrPop(PT_Uint32, E);
4779 }
4780 // Else, also load the value.
4781 return this->emitArrayElemPop(classifyPrim(E->getType()), Indices[0], E);
4782 }
4783
4784 // Create a local variable for the base.
4785 unsigned BaseOffset = allocateLocalPrimitive(Base, PT_Ptr, /*IsConst=*/true);
4786 if (!this->visit(Base))
4787 return false;
4788 if (!this->emitSetLocal(PT_Ptr, BaseOffset, E))
4789 return false;
4790
4791 // Now the vector variable for the return value.
4792 if (!Initializing) {
4793 UnsignedOrNone ResultIndex = allocateLocal(E);
4794 if (!ResultIndex)
4795 return false;
4796 if (!this->emitGetPtrLocal(*ResultIndex, E))
4797 return false;
4798 }
4799
4800 assert(Indices.size() == E->getType()->getAs<VectorType>()->getNumElements());
4801
4802 PrimType ElemT =
4804 uint32_t DstIndex = 0;
4805 for (uint32_t I : Indices) {
4806 if (!this->emitGetLocal(PT_Ptr, BaseOffset, E))
4807 return false;
4808 if (!this->emitArrayElemPop(ElemT, I, E))
4809 return false;
4810 if (!this->emitInitElem(ElemT, DstIndex, E))
4811 return false;
4812 ++DstIndex;
4813 }
4814
4815 // Leave the result pointer on the stack.
4816 assert(!DiscardResult);
4817 return true;
4818}
4819
4820template <class Emitter>
4822 const Expr *SubExpr = E->getSubExpr();
4824 return this->discard(SubExpr) && this->emitInvalid(E);
4825
4826 if (DiscardResult)
4827 return true;
4828
4829 assert(classifyPrim(E) == PT_Ptr);
4830 return this->emitDummyPtr(E, E);
4831}
4832
4833template <class Emitter>
4835 const CXXStdInitializerListExpr *E) {
4836 const Expr *SubExpr = E->getSubExpr();
4838 Ctx.getASTContext().getAsConstantArrayType(SubExpr->getType());
4839 const Record *R = getRecord(E->getType());
4840 assert(Initializing);
4841 assert(SubExpr->isGLValue());
4842
4843 if (!this->visit(SubExpr))
4844 return false;
4845 if (!this->emitConstUint8(0, E))
4846 return false;
4847 if (!this->emitArrayElemPtrPopUint8(E))
4848 return false;
4849 if (!this->emitInitFieldPtr(R->getField(0u)->Offset, E))
4850 return false;
4851
4852 PrimType SecondFieldT = classifyPrim(R->getField(1u)->Decl->getType());
4853 if (isIntegerOrBoolType(SecondFieldT)) {
4854 if (!this->emitConst(ArrayType->getSize(), SecondFieldT, E))
4855 return false;
4856 return this->emitInitField(SecondFieldT, R->getField(1u)->Offset, E);
4857 }
4858 assert(SecondFieldT == PT_Ptr);
4859
4860 if (!this->emitGetFieldPtr(R->getField(0u)->Offset, E))
4861 return false;
4862 if (!this->emitExpandPtr(E))
4863 return false;
4864 if (!this->emitConst(ArrayType->getSize(), PT_Uint64, E))
4865 return false;
4866 if (!this->emitArrayElemPtrPop(PT_Uint64, E))
4867 return false;
4868 return this->emitInitFieldPtr(R->getField(1u)->Offset, E);
4869}
4870
4871template <class Emitter>
4873 LocalScope<Emitter> BS(this);
4874 llvm::SaveAndRestore StmtExprSAR(this->InStmtExpr, true);
4875
4876 const CompoundStmt *CS = E->getSubStmt();
4877 const Stmt *Result = CS->body_back();
4878 for (const Stmt *S : CS->body()) {
4879 if (S != Result) {
4880 if (!this->visitStmt(S))
4881 return false;
4882 continue;
4883 }
4884
4885 assert(S == Result);
4886 if (const Expr *ResultExpr = dyn_cast<Expr>(S))
4887 return this->delegate(ResultExpr);
4888 if (!this->visitStmt(S))
4889 return false;
4890 return this->emitUnsupported(E);
4891 }
4892
4893 return BS.destroyLocals();
4894}
4895
4896template <class Emitter> bool Compiler<Emitter>::discard(const Expr *E) {
4897 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/true,
4898 /*NewInitializing=*/false, /*ToLValue=*/false);
4899 return this->Visit(E);
4900}
4901
4902template <class Emitter> bool Compiler<Emitter>::delegate(const Expr *E) {
4903 // We're basically doing:
4904 // OptionScope<Emitter> Scope(this, DicardResult, Initializing, ToLValue);
4905 // but that's unnecessary of course.
4906 return this->Visit(E);
4907}
4908
4910 if (const auto *PE = dyn_cast<ParenExpr>(E))
4911 return stripCheckedDerivedToBaseCasts(PE->getSubExpr());
4912
4913 if (const auto *CE = dyn_cast<CastExpr>(E);
4914 CE &&
4915 (CE->getCastKind() == CK_DerivedToBase || CE->getCastKind() == CK_NoOp))
4916 return stripCheckedDerivedToBaseCasts(CE->getSubExpr());
4917
4918 return E;
4919}
4920
4921static const Expr *stripDerivedToBaseCasts(const Expr *E) {
4922 if (const auto *PE = dyn_cast<ParenExpr>(E))
4923 return stripDerivedToBaseCasts(PE->getSubExpr());
4924
4925 if (const auto *CE = dyn_cast<CastExpr>(E);
4926 CE && (CE->getCastKind() == CK_DerivedToBase ||
4927 CE->getCastKind() == CK_UncheckedDerivedToBase ||
4928 CE->getCastKind() == CK_NoOp))
4929 return stripDerivedToBaseCasts(CE->getSubExpr());
4930
4931 return E;
4932}
4933
4934template <class Emitter> bool Compiler<Emitter>::visit(const Expr *E) {
4935 if (E->getType().isNull())
4936 return false;
4937
4938 if (E->getType()->isVoidType())
4939 return this->discard(E);
4940
4941 // Create local variable to hold the return value.
4942 if (!E->isGLValue() && !canClassify(E->getType())) {
4943 UnsignedOrNone LocalIndex = allocateLocal(
4945 if (!LocalIndex)
4946 return false;
4947
4948 if (!this->emitGetPtrLocal(*LocalIndex, E))
4949 return false;
4950 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
4951 return this->visitInitializer(E);
4952 }
4953
4954 // Otherwise,we have a primitive return value, produce the value directly
4955 // and push it on the stack.
4956 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4957 /*NewInitializing=*/false, /*ToLValue=*/ToLValue);
4958 return this->Visit(E);
4959}
4960
4961template <class Emitter>
4963 assert(!canClassify(E->getType()));
4964
4965 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4966 /*NewInitializing=*/true, /*ToLValue=*/false);
4967 return this->Visit(E) && this->emitFinishInit(E);
4968}
4969
4970template <class Emitter>
4972 assert(!canClassify(E->getType()));
4973
4974 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4975 /*NewInitializing=*/true, /*ToLValue=*/false);
4976 return this->Visit(E) && this->emitFinishInitPop(E);
4977}
4978
4979template <class Emitter> bool Compiler<Emitter>::visitAsLValue(const Expr *E) {
4980 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4981 /*NewInitializing=*/false, /*ToLValue=*/true);
4982 return this->Visit(E);
4983}
4984
4985template <class Emitter> bool Compiler<Emitter>::visitBool(const Expr *E) {
4986 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4987 /*NewInitializing=*/false, /*ToLValue=*/ToLValue);
4988
4989 OptPrimType T = classify(E->getType());
4990 if (!T) {
4991 // Convert complex values to bool.
4992 if (E->getType()->isAnyComplexType()) {
4993 if (!this->visit(E))
4994 return false;
4995 return this->emitComplexBoolCast(E);
4996 }
4997 return false;
4998 }
4999
5000 if (!this->visit(E))
5001 return false;
5002
5003 if (T == PT_Bool)
5004 return true;
5005
5006 // Convert pointers to bool.
5007 if (T == PT_Ptr)
5008 return this->emitIsNonNullPtr(E);
5009
5010 // Or Floats.
5011 if (T == PT_Float)
5012 return this->emitCastFloatingIntegralBool(getFPOptions(E), E);
5013
5014 // Or anything else we can.
5015 return this->emitCast(*T, PT_Bool, E);
5016}
5017
5018template <class Emitter>
5019bool Compiler<Emitter>::visitZeroInitializer(PrimType T, QualType QT,
5020 const Expr *E) {
5021 if (const auto *AT = QT->getAs<AtomicType>())
5022 QT = AT->getValueType();
5023
5024 switch (T) {
5025 case PT_Bool:
5026 return this->emitZeroBool(E);
5027 case PT_Sint8:
5028 return this->emitZeroSint8(E);
5029 case PT_Uint8:
5030 return this->emitZeroUint8(E);
5031 case PT_Sint16:
5032 return this->emitZeroSint16(E);
5033 case PT_Uint16:
5034 return this->emitZeroUint16(E);
5035 case PT_Sint32:
5036 return this->emitZeroSint32(E);
5037 case PT_Uint32:
5038 return this->emitZeroUint32(E);
5039 case PT_Sint64:
5040 return this->emitZeroSint64(E);
5041 case PT_Uint64:
5042 return this->emitZeroUint64(E);
5043 case PT_IntAP:
5044 return this->emitZeroIntAP(Ctx.getBitWidth(QT), E);
5045 case PT_IntAPS:
5046 return this->emitZeroIntAPS(Ctx.getBitWidth(QT), E);
5047 case PT_Ptr:
5048 return this->emitNullPtr(Ctx.getASTContext().getTargetNullPointerValue(QT),
5049 nullptr, E);
5050 case PT_MemberPtr:
5051 return this->emitNullMemberPtr(0, nullptr, E);
5052 case PT_Float: {
5053 APFloat F = APFloat::getZero(Ctx.getFloatSemantics(QT));
5054 return this->emitFloat(F, E);
5055 }
5056 case PT_FixedPoint: {
5057 auto Sem = Ctx.getASTContext().getFixedPointSemantics(QT);
5058 return this->emitConstFixedPoint(FixedPoint::zero(Sem), E);
5059 }
5060 }
5061 llvm_unreachable("unknown primitive type");
5062}
5063
5064template <class Emitter>
5065bool Compiler<Emitter>::visitZeroRecordInitializer(const Record *R,
5066 const Expr *E,
5067 bool IsCompleteClass) {
5068 assert(E);
5069 assert(R);
5070 // Fields
5071 for (const Record::Field &Field : R->fields()) {
5072 if (Field.isUnnamedBitField())
5073 continue;
5074
5075 const Descriptor *D = Field.Desc;
5076 if (D->isPrimitive()) {
5077 QualType QT = D->getType();
5078 PrimType T = D->getPrimType();
5079 if (!this->visitZeroInitializer(T, QT, E))
5080 return false;
5081 if (R->isUnion()) {
5082 if (!this->emitInitFieldActivate(T, Field.Offset, E))
5083 return false;
5084 break;
5085 }
5086 if (!this->emitInitField(T, Field.Offset, E))
5087 return false;
5088 continue;
5089 }
5090
5091 if (!this->emitGetPtrField(Field.Offset, E))
5092 return false;
5093
5094 if (D->isPrimitiveArray()) {
5095 QualType ET = D->getElemQualType();
5096 PrimType T = D->getPrimType();
5097 for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) {
5098 if (!this->visitZeroInitializer(T, ET, E))
5099 return false;
5100 if (!this->emitInitElem(T, I, E))
5101 return false;
5102 }
5103 } else if (D->isCompositeArray()) {
5104 // Can't be a vector or complex field.
5105 if (!this->visitZeroArrayInitializer(D->getType(), E))
5106 return false;
5107 } else if (D->isRecord()) {
5108 if (!this->visitZeroRecordInitializer(D->ElemRecord, E))
5109 return false;
5110 } else
5111 return false;
5112
5113 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5114 // object's first non-static named data member is zero-initialized
5115 if (R->isUnion()) {
5116 if (!this->emitFinishInitActivatePop(E))
5117 return false;
5118 break;
5119 }
5120 if (!this->emitFinishInitPop(E))
5121 return false;
5122 }
5123
5124 for (const Record::Base &B : R->bases()) {
5125 if (!this->emitGetPtrBase(B.Offset, E))
5126 return false;
5127 if (!this->visitZeroRecordInitializer(B.R, E, /*IsCompleteClass=*/false))
5128 return false;
5129 if (!this->emitFinishInitPop(E))
5130 return false;
5131 }
5132
5133 if (IsCompleteClass) {
5134 for (const Record::Base &B : R->virtual_bases()) {
5135 if (!this->emitGetPtrVirtBase(cast<CXXRecordDecl>(B.R->getDecl()), E))
5136 return false;
5137 if (!this->visitZeroRecordInitializer(B.R, E, /*IsCompleteClass=*/false))
5138 return false;
5139 if (!this->emitFinishInitPop(E))
5140 return false;
5141 }
5142 }
5143
5144 return true;
5145}
5146
5147template <class Emitter>
5148bool Compiler<Emitter>::visitZeroArrayInitializer(QualType T, const Expr *E) {
5149 assert(T->isArrayType() || T->isAnyComplexType() || T->isVectorType());
5150 const ArrayType *AT = T->getAsArrayTypeUnsafe();
5151 QualType ElemType = AT->getElementType();
5152 size_t NumElems = cast<ConstantArrayType>(AT)->getZExtSize();
5153
5154 if (OptPrimType ElemT = classify(ElemType)) {
5155 for (size_t I = 0; I != NumElems; ++I) {
5156 if (!this->visitZeroInitializer(*ElemT, ElemType, E))
5157 return false;
5158 if (!this->emitInitElem(*ElemT, I, E))
5159 return false;
5160 }
5161 return true;
5162 }
5163 if (ElemType->isRecordType()) {
5164 const Record *R = getRecord(ElemType);
5165 if (!R)
5166 return false;
5167
5168 for (size_t I = 0; I != NumElems; ++I) {
5169 if (!this->emitConstUint32(I, E))
5170 return false;
5171 if (!this->emitArrayElemPtr(PT_Uint32, E))
5172 return false;
5173 if (!this->visitZeroRecordInitializer(R, E))
5174 return false;
5175 if (!this->emitPopPtr(E))
5176 return false;
5177 }
5178 return true;
5179 }
5180 if (ElemType->isArrayType()) {
5181 for (size_t I = 0; I != NumElems; ++I) {
5182 if (!this->emitConstUint32(I, E))
5183 return false;
5184 if (!this->emitArrayElemPtr(PT_Uint32, E))
5185 return false;
5186 if (!this->visitZeroArrayInitializer(ElemType, E))
5187 return false;
5188 if (!this->emitPopPtr(E))
5189 return false;
5190 }
5191 return true;
5192 }
5193
5194 return false;
5195}
5196
5197template <class Emitter>
5198bool Compiler<Emitter>::visitAssignment(const Expr *LHS, const Expr *RHS,
5199 const Expr *E) {
5200 if (!canClassify(E->getType()))
5201 return false;
5202
5203 bool NeedsFlip = !isSideEffectFree(RHS);
5204 if (!NeedsFlip) {
5205 if (!this->visit(LHS))
5206 return false;
5207 if (!this->visit(RHS))
5208 return false;
5209 } else {
5210 if (!this->visit(RHS))
5211 return false;
5212 if (!this->visit(LHS))
5213 return false;
5214 }
5215
5216 if (LHS->getType().isVolatileQualified())
5217 return this->emitInvalidStore(LHS->getType().getTypePtr(), E);
5218
5219 // We don't support assignments in C.
5220 if (!Ctx.getLangOpts().CPlusPlus && !this->emitInvalid(E))
5221 return false;
5222
5223 PrimType RHT = classifyPrim(RHS);
5224 bool Activates = refersToUnion(LHS);
5225 bool BitField = LHS->refersToBitField();
5226
5227 if (NeedsFlip && !this->emitFlip(PT_Ptr, RHT, E))
5228 return false;
5229
5230 if (DiscardResult) {
5231 if (BitField && Activates)
5232 return this->emitStoreBitFieldActivatePop(RHT, E);
5233 if (BitField)
5234 return this->emitStoreBitFieldPop(RHT, E);
5235 if (Activates)
5236 return this->emitStoreActivatePop(RHT, E);
5237 // Otherwise, regular non-activating store.
5238 return this->emitStorePop(RHT, E);
5239 }
5240
5241 auto maybeLoad = [&](bool Result) -> bool {
5242 if (!Result)
5243 return false;
5244 // Assignments aren't necessarily lvalues in C.
5245 // Load from them in that case.
5246 if (!E->isLValue())
5247 return this->emitLoadPop(RHT, E);
5248 return true;
5249 };
5250
5251 if (BitField && Activates)
5252 return maybeLoad(this->emitStoreBitFieldActivate(RHT, E));
5253 if (BitField)
5254 return maybeLoad(this->emitStoreBitField(RHT, E));
5255 if (Activates)
5256 return maybeLoad(this->emitStoreActivate(RHT, E));
5257 // Otherwise, regular non-activating store.
5258 return maybeLoad(this->emitStore(RHT, E));
5259}
5260
5261template <class Emitter>
5262template <typename T>
5263bool Compiler<Emitter>::emitConst(T Value, PrimType Ty, SourceInfo Info) {
5264 switch (Ty) {
5265 case PT_Sint8:
5266 return this->emitConstSint8(Value, Info);
5267 case PT_Uint8:
5268 return this->emitConstUint8(Value, Info);
5269 case PT_Sint16:
5270 return this->emitConstSint16(Value, Info);
5271 case PT_Uint16:
5272 return this->emitConstUint16(Value, Info);
5273 case PT_Sint32:
5274 return this->emitConstSint32(Value, Info);
5275 case PT_Uint32:
5276 return this->emitConstUint32(Value, Info);
5277 case PT_Sint64:
5278 return this->emitConstSint64(Value, Info);
5279 case PT_Uint64:
5280 return this->emitConstUint64(Value, Info);
5281 case PT_Bool:
5282 return this->emitConstBool(Value, Info);
5283 case PT_Ptr:
5284 case PT_MemberPtr:
5285 case PT_Float:
5286 case PT_IntAP:
5287 case PT_IntAPS:
5288 case PT_FixedPoint:
5289 llvm_unreachable("Invalid integral type");
5290 break;
5291 }
5292 llvm_unreachable("unknown primitive type");
5293}
5294
5295template <class Emitter>
5296template <typename T>
5297bool Compiler<Emitter>::emitConst(T Value, const Expr *E) {
5298 return this->emitConst(Value, classifyPrim(E->getType()), E);
5299}
5300
5301template <class Emitter>
5302bool Compiler<Emitter>::emitConst(const APSInt &Value, PrimType Ty,
5303 SourceInfo Info) {
5304 if (Ty == PT_IntAPS)
5305 return this->emitConstIntAPS(Value, Info);
5306 if (Ty == PT_IntAP)
5307 return this->emitConstIntAP(Value, Info);
5308
5309 if (Value.isSigned())
5310 return this->emitConst(Value.getSExtValue(), Ty, Info);
5311 return this->emitConst(Value.getZExtValue(), Ty, Info);
5312}
5313
5314template <class Emitter>
5315bool Compiler<Emitter>::emitConst(const APInt &Value, PrimType Ty,
5316 SourceInfo Info) {
5317 if (Ty == PT_IntAPS)
5318 return this->emitConstIntAPS(Value, Info);
5319 if (Ty == PT_IntAP)
5320 return this->emitConstIntAP(Value, Info);
5321
5322 if (isSignedType(Ty))
5323 return this->emitConst(Value.getSExtValue(), Ty, Info);
5324 return this->emitConst(Value.getZExtValue(), Ty, Info);
5325}
5326
5327template <class Emitter>
5328bool Compiler<Emitter>::emitConst(const APSInt &Value, const Expr *E) {
5329 return this->emitConst(Value, classifyPrim(E->getType()), E);
5330}
5331
5332template <class Emitter>
5334 bool IsConst,
5335 bool IsVolatile,
5336 ScopeKind SC) {
5337 // FIXME: There are cases where Src.isExpr() is wrong, e.g.
5338 // (int){12} in C. Consider using Expr::isTemporaryObject() instead
5339 // or isa<MaterializeTemporaryExpr>().
5340 Descriptor *D = P.createDescriptor(Src, Ty, nullptr, IsConst, Src.isExpr(),
5341 /*IsMutable=*/false, IsVolatile);
5343 Scope::Local Local = this->createLocal(D);
5344 if (auto *VD = Src.asValueDecl())
5345 Locals.insert({VD, Local});
5346 VarScope->addForScopeKind(Local, SC);
5347 return Local.Offset;
5348}
5349
5350template <class Emitter>
5352 ScopeKind SC) {
5353 const ValueDecl *Key = nullptr;
5354 const Expr *Init = nullptr;
5355 bool IsTemporary = false;
5356 if (auto *VD = Src.asValueDecl()) {
5357 Key = VD;
5358
5359 if (const auto *VarD = dyn_cast<VarDecl>(VD))
5360 Init = VarD->getInit();
5361 }
5362 if (const auto *E = Src.asExpr()) {
5363 IsTemporary = true;
5364 if (Ty.isNull())
5365 Ty = E->getType();
5366 }
5367
5368 Descriptor *D = P.createDescriptor(
5369 Src, Ty.getTypePtr(), Ty.isConstQualified(), IsTemporary,
5370 /*IsMutable=*/false, /*IsVolatile=*/Ty.isVolatileQualified(), Init);
5371 if (!D)
5372 return std::nullopt;
5374
5375 Scope::Local Local = this->createLocal(D);
5376 if (Key)
5377 Locals.insert({Key, Local});
5378 VarScope->addForScopeKind(Local, SC);
5379 return Local.Offset;
5380}
5381
5382template <class Emitter>
5384 QualType Ty = E->getType();
5385 assert(!Ty->isRecordType());
5386
5387 Descriptor *D = P.createDescriptor(E, Ty.getTypePtr(), Ty.isConstQualified(),
5388 /*IsTemporary=*/true);
5389
5390 if (!D)
5391 return std::nullopt;
5392
5393 Scope::Local Local = this->createLocal(D);
5395 assert(S);
5396 // Attach to topmost scope.
5397 while (S->getParent())
5398 S = S->getParent();
5399 assert(S && !S->getParent());
5400 S->addLocal(Local);
5401 return Local.Offset;
5402}
5403
5404template <class Emitter>
5406 if (const PointerType *PT = dyn_cast<PointerType>(Ty))
5407 return PT->getPointeeType()->getAsCanonical<RecordType>();
5408 return Ty->getAsCanonical<RecordType>();
5409}
5410
5411template <class Emitter> Record *Compiler<Emitter>::getRecord(QualType Ty) {
5412 if (const auto *RecordTy = getRecordTy(Ty))
5413 return getRecord(RecordTy->getDecl()->getDefinitionOrSelf());
5414 return nullptr;
5415}
5416
5417template <class Emitter>
5419 return P.getOrCreateRecord(RD);
5420}
5421
5422template <class Emitter>
5424 return Ctx.getOrCreateFunction(FD);
5425}
5426
5427template <class Emitter>
5428bool Compiler<Emitter>::visitExpr(const Expr *E, bool DestroyToplevelScope) {
5430
5431 auto maybeDestroyLocals = [&]() -> bool {
5432 if (DestroyToplevelScope)
5433 return RootScope.destroyLocals() && this->emitCheckAllocations(E);
5434 return this->emitCheckAllocations(E);
5435 };
5436
5437 // Void expressions.
5438 if (E->getType()->isVoidType()) {
5439 if (!visit(E))
5440 return false;
5441 return this->emitRetVoid(E) && maybeDestroyLocals();
5442 }
5443
5444 // Expressions with a primitive return type.
5445 if (OptPrimType T = classify(E)) {
5446 if (!visit(E))
5447 return false;
5448
5449 return this->emitRet(*T, E) && maybeDestroyLocals();
5450 }
5451
5452 // Expressions with a composite return type.
5453 // For us, that means everything we don't
5454 // have a PrimType for.
5455 if (UnsignedOrNone LocalOffset = this->allocateLocal(E)) {
5456 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalOffset));
5457 if (!this->emitGetPtrLocal(*LocalOffset, E))
5458 return false;
5459
5460 if (!visitInitializer(E))
5461 return false;
5462 // We are destroying the locals AFTER the Ret op.
5463 // The Ret op needs to copy the (alive) values, but the
5464 // destructors may still turn the entire expression invalid.
5465 return this->emitRetValue(E) && maybeDestroyLocals();
5466 }
5467
5468 return maybeDestroyLocals() && false;
5469}
5470
5471template <class Emitter>
5473 bool DestroyToplevelScope) {
5474 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
5475 /*NewInitializing=*/false, /*ToLValue=*/true);
5476
5477 return this->visitExpr(E, DestroyToplevelScope);
5478}
5479
5480template <class Emitter>
5482
5483 auto R = this->visitVarDecl(VD, VD->getInit(), /*Toplevel=*/true);
5484
5485 if (R.notCreated())
5486 return R;
5487
5488 if (R)
5489 return true;
5490
5491 if (!R && Context::shouldBeGloballyIndexed(VD)) {
5492 if (auto GlobalIndex = P.getGlobal(VD)) {
5493 Block *GlobalBlock = P.getGlobal(*GlobalIndex);
5494 auto &GD = GlobalBlock->getBlockDesc<GlobalInlineDescriptor>();
5495
5497 GlobalBlock->invokeDtor();
5498 }
5499 }
5500
5501 return R;
5502}
5503
5504/// Toplevel visitDeclAndReturn().
5505/// We get here from evaluateAsInitializer().
5506/// We need to evaluate the initializer and return its value.
5507template <class Emitter>
5509 bool ConstantContext) {
5510 // We only create variables if we're evaluating in a constant context.
5511 // Otherwise, just evaluate the initializer and return it.
5512 if (!ConstantContext) {
5513 DeclScope<Emitter> LS(this, VD);
5514 if (!this->visit(Init))
5515 return false;
5516 return this->emitRet(classify(Init).value_or(PT_Ptr), VD) &&
5517 LS.destroyLocals() && this->emitCheckAllocations(VD);
5518 }
5519
5520 LocalScope<Emitter> VDScope(this);
5521 if (!this->visitVarDecl(VD, Init, /*Toplevel=*/true))
5522 return false;
5523
5524 OptPrimType VarT = classify(VD->getType());
5525 bool IsReference = VD->getType()->isReferenceType();
5527 auto GlobalIndex = P.getGlobal(VD);
5528 assert(GlobalIndex); // visitVarDecl() didn't return false.
5529 if (VarT) {
5530 if (!this->emitGetGlobalUnchecked(*VarT, *GlobalIndex, VD))
5531 return false;
5532 } else {
5533 if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
5534 return false;
5535 }
5536 } else {
5537 auto Local = Locals.find(VD);
5538 assert(Local != Locals.end()); // Same here.
5539 if (VarT) {
5540 if (IsReference) {
5541 if (!this->emitGetRefLocal(Local->second.Offset, VD))
5542 return false;
5543 } else if (!this->emitGetLocal(*VarT, Local->second.Offset, VD))
5544 return false;
5545 } else {
5546 if (!this->emitGetPtrLocal(Local->second.Offset, VD))
5547 return false;
5548 }
5549 }
5550
5551 // Return the value.
5552 if (!this->emitRet(VarT.value_or(PT_Ptr), VD)) {
5553 // If the Ret above failed and this is a global variable, mark it as
5554 // uninitialized, even everything else succeeded.
5556 auto GlobalIndex = P.getGlobal(VD);
5557 assert(GlobalIndex);
5558 Block *GlobalBlock = P.getGlobal(*GlobalIndex);
5559 auto &GD = GlobalBlock->getBlockDesc<GlobalInlineDescriptor>();
5560
5562 GlobalBlock->invokeDtor();
5563 }
5564 return false;
5565 }
5566
5567 return VDScope.destroyLocals() && this->emitCheckAllocations(VD);
5568}
5569
5570template <class Emitter>
5572 const Expr *Init,
5573 bool Toplevel) {
5574 QualType VarTy = VD->getType();
5575 // We don't know what to do with these, so just return false.
5576 if (VarTy.isNull())
5577 return false;
5578
5579 // This case is EvalEmitter-only. If we won't create any instructions for the
5580 // initializer anyway, don't bother creating the variable in the first place.
5581 if (!this->isActive())
5583
5584 OptPrimType VarT = classify(VD->getType());
5585
5586 if (Init && Init->isValueDependent())
5587 return false;
5588
5590 auto checkDecl = [&]() -> bool {
5591 bool NeedsOp = !Toplevel && VD->isLocalVarDecl() && VD->isStaticLocal();
5592 return !NeedsOp || this->emitCheckDecl(VD, VD);
5593 };
5594
5596 UnsignedOrNone GlobalIndex = P.getGlobal(VD);
5597 if (GlobalIndex) {
5598 // The global was previously created but the initializer failed.
5599 if (!P.getGlobal(*GlobalIndex)->isInitialized())
5600 return false;
5601 // We've already seen and initialized this global.
5602 if (P.isGlobalInitialized(*GlobalIndex))
5603 return checkDecl();
5604 // The previous attempt at initialization might've been unsuccessful,
5605 // so let's try this one.
5606 } else if ((GlobalIndex =
5607 P.createGlobal(VD, Init, VariablesAreConstexprUnknown))) {
5608 } else {
5609 return false;
5610 }
5611 if (!Init)
5612 return true;
5613
5614 if (!checkDecl())
5615 return false;
5616
5617 if (VarT) {
5618 if (!this->visit(Init))
5619 return false;
5620
5621 return this->emitInitGlobal(*VarT, *GlobalIndex, VD);
5622 }
5623
5624 if (!this->emitGetPtrGlobal(*GlobalIndex, Init))
5625 return false;
5626
5627 if (!this->emitStartInit(Init))
5628 return false;
5629
5630 if (!visitInitializer(Init))
5631 return false;
5632
5633 if (!this->emitEndInit(Init))
5634 return false;
5635
5636 return this->emitFinishInitGlobal(Init);
5637 }
5638 // Local variables.
5640
5641 if (VarT) {
5642 unsigned Offset = this->allocateLocalPrimitive(
5643 VD, *VarT, VarTy.isConstQualified(), VarTy.isVolatileQualified(),
5645
5646 if (!Init || Init->getType()->isVoidType())
5647 return true;
5648
5649 // If this is a toplevel declaration, create a scope for the
5650 // initializer.
5651 if (Toplevel) {
5653 if (!this->visit(Init))
5654 return false;
5655 return this->emitSetLocal(*VarT, Offset, VD) && Scope.destroyLocals();
5656 }
5657 if (!this->visit(Init))
5658 return false;
5659
5660 if (VarTy->isReferenceType()) {
5661 // [C++26][decl.ref]
5662 // The object designated by such a glvalue can be outside its lifetime
5663 // Because a null pointer value or a pointer past the end of an object
5664 // does not point to an object, a reference in a well-defined program
5665 // cannot refer to such things;
5666 assert(classifyPrim(VarTy) == PT_Ptr);
5667 if (!this->emitCheckRefInit(Init))
5668 return false;
5669 }
5670
5671 return this->emitSetLocal(*VarT, Offset, VD);
5672 }
5673 // Local composite variables.
5674 if (UnsignedOrNone Offset =
5675 this->allocateLocal(VD, VarTy, ScopeKind::Block)) {
5676 if (!Init)
5677 return true;
5678
5679 if (!this->emitGetPtrLocal(*Offset, Init))
5680 return false;
5681
5682 return visitInitializerPop(Init);
5683 }
5684 return false;
5685}
5686
5687template <class Emitter>
5689 assert(!canClassify(VD->getType()));
5690
5692 // Create a local variable to use as the instance.
5693 QualType Ty = VD->getType();
5694 Descriptor *D =
5695 P.createDescriptor(VD, Ty.getTypePtr(), /*IsConst=*/Ty.isConstQualified(),
5696 /*IsTemporary=*/false, /*IsMutable=*/false,
5697 /*IsVolatile=*/Ty.isVolatileQualified(), nullptr);
5698 if (!D)
5699 return false;
5700
5701 // FIXME: Would be nice if we didn't allocate the descriptor at all in this
5702 // case.
5703 if (D->hasTrivialDtor())
5704 return true;
5705
5706 Scope::Local Local = this->createLocal(D);
5707 Locals.insert({VD, Local});
5708 VarScope->addForScopeKind(Local, ScopeKind::Block);
5709
5710 if (!this->emitGetPtrLocal(Local.Offset, VD))
5711 return false;
5712
5713 if (!this->visitAPValueInitializer(Value, VD, Ty))
5714 return false;
5715
5716 return this->emitDestructionPop(D, VD);
5717}
5718
5720public:
5722 explicit ParamFinder() {}
5723
5724 bool VisitDeclRefExpr(const DeclRefExpr *E) override {
5725 if (const auto *P = dyn_cast<ParmVarDecl>(E->getDecl()))
5726 FoundParams.insert(P);
5727 return true;
5728 }
5729};
5730
5731/// Evaluate the \p Condition as if it was in the body of \p Callee.
5732/// Specifically, all the parameters of the callee are available to use
5733/// for the condition, and their values are given by \p Args (and \p This).
5734///
5735// Since this is a somewhat niche feature, we're abusing a few other mechanisms
5736// to implement this.
5737//
5738// We don't create an actual function frame but instead register the parameters
5739// as local variables.
5740//
5741// So we evaluate something like:
5742//
5743// bool thisfunc() {
5744// auto Arg0 = Args[0];
5745// ...
5746// return Condition;
5747// }
5748//
5749template <class Emitter>
5752 const Expr *This,
5753 const Expr *Condition) {
5754 // Instead of evaluating all parameters and trying to ignore failure,
5755 // we collect all the parameters used in the condition and only evaluate
5756 // those. Note that we still ignore failure in the loop below because the
5757 // failure might be inconsequential in the end,
5758 // e.g. in the case of `true || x`.
5759 ParamFinder PF;
5761
5762 LocalScope<Emitter> ArgScope(this);
5763 for (const ParmVarDecl *PVD : PF.FoundParams) {
5764 unsigned ParamIndex = 0;
5765 for (const ParmVarDecl *P : Callee->parameters()) {
5766 if (P == PVD)
5767 break;
5768 ++ParamIndex;
5769 }
5770
5771 const Expr *Arg = Args[ParamIndex];
5772 const ParmVarDecl *Param = Callee->getParamDecl(ParamIndex);
5773 if (OptPrimType ParamT = classify(Param->getType())) {
5774 unsigned ArgOffset =
5775 allocateLocalPrimitive(Param, *ParamT, /*IsConst=*/true);
5776 if (!this->visit(Arg))
5777 continue;
5778 if (!this->emitSetLocal(*ParamT, ArgOffset, Arg))
5779 return false;
5780 } else {
5781 UnsignedOrNone ArgOffset = this->allocateLocal(Param, Param->getType());
5782 if (!ArgOffset)
5783 return false;
5784 if (!this->emitGetPtrLocal(*ArgOffset, Arg))
5785 return false;
5786 if (!this->visitInitializerPop(Arg))
5787 continue;
5788 }
5789 }
5790
5791 if (This) {
5792 // We abuse the init stack for this and tell it to use
5793 // either a local variable or another decl for the This pointer.
5794 this->InitStackActive = true;
5795
5796 if (This->getType()->isPointerType()) {
5797 // Nothing to do here, the evaluation will fail if the instance
5798 // pointer is used.
5799 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(This)) {
5800 InitStack.push_back(InitLink::Decl(DRE->getDecl()));
5801 } else {
5802 assert(!canClassify(This->getType()));
5803 UnsignedOrNone ArgOffset = this->allocateLocal(This, This->getType());
5804 if (!ArgOffset)
5805 return false;
5806 if (!this->emitGetPtrLocal(*ArgOffset, This))
5807 return false;
5808 if (!this->visitInitializerPop(This))
5809 return false;
5810 this->InitStack.push_back(InitLink::Temp(*ArgOffset));
5811 }
5812 }
5813
5814 // Destruction of the argument values is part of the callee frame,
5815 // so we simply ignore them here.
5816 this->VarScope = nullptr;
5817
5818 LocalScope<Emitter> RetScope(this);
5819 if (!this->visit(Condition))
5820 return false;
5821 if (!RetScope.destroyLocals())
5822 return false;
5823
5824 // Result of the condition should be on the stack.
5825 return this->emitRet(PT_Bool, Condition);
5826}
5827
5828template <class Emitter>
5830 SourceInfo Info) {
5831 assert(!Val.isIndeterminate() && "Needs to be checked before");
5832 assert(!DiscardResult);
5833 if (Val.isInt())
5834 return this->emitConst(Val.getInt(), ValType, Info);
5835 if (Val.isFloat())
5836 return this->emitFloat(Val.getFloat(), Info);
5837
5838 if (Val.isMemberPointer()) {
5839 if (const ValueDecl *MemberDecl = Val.getMemberPointerDecl()) {
5840 if (!this->emitGetMemberPtr(MemberDecl, Info))
5841 return false;
5842
5843 bool IsDerived = Val.isMemberPointerToDerivedMember();
5844 // Apply the member pointer path.
5845 for (const CXXRecordDecl *PathEntry : Val.getMemberPointerPath()) {
5846 if (!this->emitCopyMemberPtrPath(PathEntry, IsDerived, Info))
5847 return false;
5848 }
5849
5850 return true;
5851 }
5852 return this->emitNullMemberPtr(0, nullptr, Info);
5853 }
5854
5855 if (Val.isLValue()) {
5856 if (Val.isNullPointer())
5857 return this->emitNull(ValType, 0, nullptr, Info);
5858
5861
5862 if (const Expr *BaseExpr = Base.dyn_cast<const Expr *>())
5863 return this->visit(BaseExpr);
5864 if (const auto *VD = Base.dyn_cast<const ValueDecl *>()) {
5865 if (!this->visitDeclRef(VD, Info.asExpr()))
5866 return false;
5867
5868 QualType EntryType = VD->getType();
5869 for (auto &Entry : Path) {
5870 if (EntryType->isArrayType()) {
5871 uint64_t Index = Entry.getAsArrayIndex();
5872 QualType ElemType =
5873 EntryType->getAsArrayTypeUnsafe()->getElementType();
5874 if (!this->emitConst(Index, PT_Uint64, Info))
5875 return false;
5876 if (!this->emitArrayElemPtrPop(PT_Uint64, Info))
5877 return false;
5878 EntryType = ElemType;
5879 } else {
5880 assert(EntryType->isRecordType());
5881 const Record *EntryRecord = getRecord(EntryType);
5882 if (!EntryRecord)
5883 return false;
5884
5885 const Decl *BaseOrMember = Entry.getAsBaseOrMember().getPointer();
5886 if (const auto *FD = dyn_cast<FieldDecl>(BaseOrMember)) {
5887 unsigned EntryOffset = EntryRecord->getField(FD)->Offset;
5888 if (!this->emitGetPtrFieldPop(EntryOffset, Info))
5889 return false;
5890 EntryType = FD->getType();
5891 } else {
5892 const auto *Base = cast<CXXRecordDecl>(BaseOrMember);
5893 if (const Record::Base *B = EntryRecord->getBaseOrNull(Base)) {
5894 if (!this->emitGetPtrBasePop(B->Offset, /*NullOK=*/false, Info))
5895 return false;
5896 } else {
5897 // Must be a virtual base.
5898 assert(EntryRecord->findVirtualBase(Base));
5899 if (!this->emitGetPtrVirtBasePop(Base, Info))
5900 return false;
5901 }
5902 EntryType = Ctx.getASTContext().getCanonicalTagType(Base);
5903 }
5904 }
5905 }
5906
5907 return true;
5908 }
5909 }
5910
5911 return false;
5912}
5913
5914template <class Emitter>
5916 SourceInfo Info, QualType T,
5917 bool IsCompleteClass) {
5918 if (Val.isStruct()) {
5919 const Record *R = this->getRecord(T);
5920 assert(R);
5921
5922 assert(R->getNumBases() == Val.getStructNumBases());
5923 if (IsCompleteClass)
5924 assert(R->getNumVirtualBases() == Val.getStructNumVirtualBases());
5925
5926 for (unsigned I = 0, N = Val.getStructNumBases(); I != N; ++I) {
5927 const APValue &B = Val.getStructBase(I);
5928 if (B.isIndeterminate())
5929 continue;
5930 const Record::Base *RB = R->getBase(I);
5931 QualType BaseType = Ctx.getASTContext().getCanonicalTagType(RB->Decl);
5932
5933 if (!this->emitGetPtrBase(RB->Offset, Info))
5934 return false;
5935 if (!this->visitAPValueInitializer(B, Info, BaseType,
5936 /*IsCompleteClass=*/false))
5937 return false;
5938 if (!this->emitFinishInitPop(Info))
5939 return false;
5940 }
5941
5942 for (unsigned I = 0, N = Val.getStructNumFields(); I != N; ++I) {
5943 const APValue &F = Val.getStructField(I);
5944 if (F.isIndeterminate())
5945 continue;
5946 const Record::Field *RF = R->getField(I);
5947 QualType FieldType = RF->Decl->getType();
5948 // Fields.
5949 if (OptPrimType PT = classify(FieldType)) {
5950 if (!this->visitAPValue(F, *PT, Info))
5951 return false;
5952 if (!this->emitInitField(*PT, RF->Offset, Info))
5953 return false;
5954 } else {
5955 if (!this->emitGetPtrField(RF->Offset, Info))
5956 return false;
5957 if (!this->visitAPValueInitializer(F, Info, FieldType))
5958 return false;
5959 if (!this->emitFinishInitPop(Info))
5960 return false;
5961 }
5962 }
5963
5964 // Virtual Bases.
5965 if (IsCompleteClass) {
5966 for (unsigned I = 0, N = Val.getStructNumVirtualBases(); I != N; ++I) {
5967 const APValue &B = Val.getStructVirtualBase(I);
5968 if (B.isIndeterminate())
5969 continue;
5970 const Record::Base *RB = R->getVirtualBase(I);
5971 QualType BaseType = Ctx.getASTContext().getCanonicalTagType(RB->Decl);
5972
5973 if (!this->emitGetPtrVirtBase(cast<CXXRecordDecl>(RB->R->getDecl()),
5974 Info))
5975 return false;
5976 if (!this->visitAPValueInitializer(B, Info, BaseType,
5977 /*IsCompleteClass=*/false))
5978 return false;
5979 if (!this->emitFinishInitPop(Info))
5980 return false;
5981 }
5982 }
5983
5984 return true;
5985 }
5986 if (Val.isUnion()) {
5987 const FieldDecl *UnionField = Val.getUnionField();
5988 if (!UnionField)
5989 return true;
5990 const Record *R = this->getRecord(T);
5991 assert(R);
5992 const APValue &F = Val.getUnionValue();
5993 if (F.isIndeterminate())
5994 return true;
5995 const Record::Field *RF = R->getField(UnionField);
5996 QualType FieldType = RF->Decl->getType();
5997
5998 if (OptPrimType PT = classify(FieldType)) {
5999 if (!this->visitAPValue(F, *PT, Info))
6000 return false;
6001 if (RF->isBitField())
6002 return this->emitInitBitFieldActivate(*PT, RF->Offset, RF->bitWidth(),
6003 Info);
6004 return this->emitInitFieldActivate(*PT, RF->Offset, Info);
6005 }
6006
6007 if (!this->emitGetPtrField(RF->Offset, Info))
6008 return false;
6009 if (!this->emitActivate(Info))
6010 return false;
6011 if (!this->visitAPValueInitializer(F, Info, FieldType))
6012 return false;
6013 return this->emitPopPtr(Info);
6014 }
6015 if (Val.isArray()) {
6016 unsigned InitializedElems = Val.getArrayInitializedElts();
6017 const auto *ArrType = T->getAsArrayTypeUnsafe();
6018 QualType ElemType = ArrType->getElementType();
6019 OptPrimType ElemT = classify(ElemType);
6020
6021 for (unsigned A = 0, AN = Val.getArraySize(); A != AN; ++A) {
6022 const APValue &Elem = A >= InitializedElems
6023 ? Val.getArrayFiller()
6024 : Val.getArrayInitializedElt(A);
6025 if (Elem.isIndeterminate())
6026 continue;
6027
6028 if (ElemT) {
6029 if (!this->visitAPValue(Elem, *ElemT, Info))
6030 return false;
6031 if (!this->emitInitElem(*ElemT, A, Info))
6032 return false;
6033 } else {
6034 if (!this->emitConstUint32(A, Info))
6035 return false;
6036 if (!this->emitArrayElemPtrUint32(Info))
6037 return false;
6038 if (!this->visitAPValueInitializer(Elem, Info, ElemType))
6039 return false;
6040 if (!this->emitPopPtr(Info))
6041 return false;
6042 }
6043 }
6044 return true;
6045 }
6046 // TODO: Other types.
6047
6048 return false;
6049}
6050
6051template <class Emitter>
6053 unsigned BuiltinID) {
6054 if (BuiltinID == Builtin::BI__builtin_constant_p) {
6055 // Void argument is always invalid and harder to handle later.
6056 if (E->getArg(0)->getType()->isVoidType()) {
6057 if (DiscardResult)
6058 return true;
6059 return this->emitConst(0, E);
6060 }
6061
6062 if (!this->emitStartSpeculation(E))
6063 return false;
6064 LabelTy EndLabel = this->getLabel();
6065 if (!this->speculate(E, EndLabel))
6066 return false;
6067 if (!this->emitEndSpeculation(E))
6068 return false;
6069 this->fallthrough(EndLabel);
6070 if (DiscardResult)
6071 return this->emitPop(classifyPrim(E), E);
6072 return true;
6073 }
6074
6075 // For these, we're expected to ultimately return an APValue pointing
6076 // to the CallExpr. This is needed to get the correct codegen.
6077 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6078 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString ||
6079 BuiltinID == Builtin::BI__builtin_ptrauth_sign_constant ||
6080 BuiltinID == Builtin::BI__builtin_function_start) {
6081 if (DiscardResult)
6082 return true;
6083 return this->emitDummyPtr(E, E);
6084 }
6085
6087 OptPrimType ReturnT = classify(E);
6088
6089 // Non-primitive return type. Prepare storage.
6090 if (!Initializing && !ReturnT && !ReturnType->isVoidType()) {
6091 UnsignedOrNone LocalIndex = allocateLocal(E);
6092 if (!LocalIndex)
6093 return false;
6094 if (!this->emitGetPtrLocal(*LocalIndex, E))
6095 return false;
6096 }
6097
6098 // Prepare function arguments including special cases.
6099 switch (BuiltinID) {
6100 case Builtin::BI__builtin_object_size:
6101 case Builtin::BI__builtin_dynamic_object_size: {
6102 assert(E->getNumArgs() == 2);
6103 const Expr *Arg0 = E->getArg(0);
6104 if (Arg0->isGLValue()) {
6105 if (!this->visit(Arg0))
6106 return false;
6107
6108 } else {
6110 return false;
6111 }
6112 if (!this->visit(E->getArg(1)))
6113 return false;
6114
6115 } break;
6116 case Builtin::BI__assume:
6117 case Builtin::BI__builtin_assume:
6118 // Argument is not evaluated.
6119 break;
6120 case Builtin::BI__atomic_is_lock_free:
6121 case Builtin::BI__atomic_always_lock_free: {
6122 assert(E->getNumArgs() == 2);
6123 if (!this->visit(E->getArg(0)))
6124 return false;
6125 if (!this->visitAsLValue(E->getArg(1)))
6126 return false;
6127 } break;
6128
6129 default:
6130 if (!Context::isUnevaluatedBuiltin(BuiltinID)) {
6131 // Put arguments on the stack.
6132 for (const auto *Arg : E->arguments()) {
6133 if (!this->visit(Arg))
6134 return false;
6135 }
6136 }
6137 }
6138
6139 if (!this->emitCallBI(E, BuiltinID, E))
6140 return false;
6141
6142 if (DiscardResult && !ReturnType->isVoidType())
6143 return this->emitPop(ReturnT.value_or(PT_Ptr), E);
6144
6145 return true;
6146}
6147
6148template <class Emitter>
6150 if (E->containsErrors())
6151 return false;
6152 const FunctionDecl *FuncDecl = E->getDirectCallee();
6153
6154 if (FuncDecl) {
6155 if (unsigned BuiltinID = FuncDecl->getBuiltinID())
6156 return VisitBuiltinCallExpr(E, BuiltinID);
6157
6158 // Calls to replaceable operator new/operator delete.
6160 if (FuncDecl->getDeclName().isAnyOperatorNew())
6161 return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_new);
6162 assert(FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
6163 FuncDecl->getDeclName().getCXXOverloadedOperator() ==
6164 OO_Array_Delete);
6165 return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_delete);
6166 }
6167
6168 // Explicit calls to trivial destructors
6169 if (const auto *DD = dyn_cast<CXXDestructorDecl>(FuncDecl);
6170 DD && DD->isTrivial()) {
6171 const auto *MemberCall = cast<CXXMemberCallExpr>(E);
6172 if (!this->visit(MemberCall->getImplicitObjectArgument()))
6173 return false;
6174 return this->emitCheckDestruction(E) && this->emitEndLifetime(E) &&
6175 this->emitPopPtr(E);
6176 }
6177 }
6178
6179 LocalScope<Emitter> CallScope(this, ScopeKind::Call);
6180
6181 QualType ReturnType = E->getCallReturnType(Ctx.getASTContext());
6183 bool HasRVO = !ReturnType->isVoidType() && !T;
6184
6185 if (HasRVO) {
6186 if (DiscardResult) {
6187 // If we need to discard the return value but the function returns its
6188 // value via an RVO pointer, we need to create one such pointer just
6189 // for this call.
6190 if (UnsignedOrNone LocalIndex = allocateLocal(E)) {
6191 if (!this->emitGetPtrLocal(*LocalIndex, E))
6192 return false;
6193 }
6194 } else {
6195 // We need the result. Prepare a pointer to return or
6196 // dup the current one.
6197 if (!Initializing) {
6198 if (UnsignedOrNone LocalIndex = allocateLocal(E)) {
6199 if (!this->emitGetPtrLocal(*LocalIndex, E))
6200 return false;
6201 }
6202 }
6203 if (!this->emitDupPtr(E))
6204 return false;
6205 }
6206 }
6207
6208 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
6209 const Expr *ReversedArgs[2];
6210
6211 bool IsAssignmentOperatorCall = false;
6212 bool ActivateLHS = false;
6213 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
6214 OCE && OCE->isAssignmentOp()) {
6215 // Just like with regular assignments, we need to special-case assignment
6216 // operators here and evaluate the RHS (the second arg) before the LHS (the
6217 // first arg). We fix this by using a Flip op later.
6218 assert(Args.size() == 2);
6219 const CXXRecordDecl *LHSRecord = Args[0]->getType()->getAsCXXRecordDecl();
6220 ActivateLHS = LHSRecord && LHSRecord->hasTrivialDefaultConstructor();
6221 IsAssignmentOperatorCall = true;
6222 ReversedArgs[0] = Args[1];
6223 ReversedArgs[1] = Args[0];
6224 Args = ReversedArgs;
6225 }
6226 // Calling a static operator will still
6227 // pass the instance, but we don't need it.
6228 // Discard it here.
6229 if (isa<CXXOperatorCallExpr>(E)) {
6230 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl);
6231 MD && MD->isStatic()) {
6232 if (!this->discard(E->getArg(0)))
6233 return false;
6234 // Drop first arg.
6235 Args = Args.drop_front();
6236 }
6237 }
6238
6239 bool Devirtualized = false;
6240 UnsignedOrNone CalleeOffset = std::nullopt;
6241 // Add the (optional, implicit) This pointer.
6242 if (const auto *MC = dyn_cast<CXXMemberCallExpr>(E)) {
6243 if (!FuncDecl && classifyPrim(E->getCallee()) == PT_MemberPtr) {
6244 // If we end up creating a CallPtr op for this, we need the base of the
6245 // member pointer as the instance pointer, and later extract the function
6246 // decl as the function pointer.
6247 const Expr *Callee = E->getCallee();
6248 CalleeOffset =
6249 this->allocateLocalPrimitive(Callee, PT_MemberPtr, /*IsConst=*/true);
6250 if (!this->visit(Callee))
6251 return false;
6252 if (!this->emitSetLocal(PT_MemberPtr, *CalleeOffset, E))
6253 return false;
6254 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
6255 return false;
6256 if (!this->emitGetMemberPtrBase(E))
6257 return false;
6258 } else {
6259 const auto *InstancePtr = MC->getImplicitObjectArgument();
6260 if (isa_and_nonnull<CXXDestructorDecl>(CompilingFunction) ||
6261 isa_and_nonnull<CXXConstructorDecl>(CompilingFunction)) {
6262 const auto *Stripped = stripCheckedDerivedToBaseCasts(InstancePtr);
6263 if (isa<CXXThisExpr>(Stripped)) {
6264 FuncDecl =
6265 cast<CXXMethodDecl>(FuncDecl)->getCorrespondingMethodInClass(
6266 Stripped->getType()->getPointeeType()->getAsCXXRecordDecl());
6267 Devirtualized = true;
6268 if (!this->visit(Stripped))
6269 return false;
6270 } else {
6271 if (!this->visit(InstancePtr))
6272 return false;
6273 }
6274 } else {
6275 if (!this->visit(InstancePtr))
6276 return false;
6277 }
6278 }
6279 } else if (const auto *PD =
6280 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee())) {
6281 if (!this->emitCheckPseudoDtor(E))
6282 return false;
6283 const Expr *Base = PD->getBase();
6284 // E.g. `using T = int; 0.~T();`.
6285 if (OptPrimType BaseT = classify(Base); !BaseT || BaseT != PT_Ptr)
6286 return this->discard(Base);
6287 if (!this->visit(Base))
6288 return false;
6289 return this->emitPseudoDtor(E);
6290 } else if (!FuncDecl) {
6291 const Expr *Callee = E->getCallee();
6292 CalleeOffset =
6293 this->allocateLocalPrimitive(Callee, PT_Ptr, /*IsConst=*/true);
6294 if (!this->visit(Callee))
6295 return false;
6296 if (!this->emitSetLocal(PT_Ptr, *CalleeOffset, E))
6297 return false;
6298 }
6299
6300 if (!this->visitCallArgs(Args, FuncDecl, ActivateLHS,
6302 return false;
6303
6304 // Undo the argument reversal we did earlier.
6305 if (IsAssignmentOperatorCall) {
6306 assert(Args.size() == 2);
6307 PrimType Arg1T = classify(Args[0]).value_or(PT_Ptr);
6308 PrimType Arg2T = classify(Args[1]).value_or(PT_Ptr);
6309 if (!this->emitFlip(Arg2T, Arg1T, E))
6310 return false;
6311 }
6312
6313 if (FuncDecl) {
6314 const Function *Func = getFunction(FuncDecl);
6315 if (!Func)
6316 return false;
6317
6318 // In error cases, the function may be called with fewer arguments than
6319 // parameters.
6320 if (E->getNumArgs() < Func->getNumWrittenParams())
6321 return false;
6322
6323 assert(HasRVO == Func->hasRVO());
6324
6325 bool HasQualifier = false;
6326 if (const auto *ME = dyn_cast<MemberExpr>(E->getCallee()))
6327 HasQualifier = ME->hasQualifier();
6328
6329 bool IsVirtual = false;
6330 if (const auto *MD = dyn_cast<CXXMethodDecl>(FuncDecl))
6331 IsVirtual = !Devirtualized && MD->isVirtual();
6332
6333 // In any case call the function. The return value will end up on the stack
6334 // and if the function has RVO, we already have the pointer on the stack to
6335 // write the result into.
6336 if (IsVirtual && !HasQualifier) {
6337 uint32_t VarArgSize = 0;
6338 unsigned NumParams =
6339 Func->getNumWrittenParams() +
6340 (isa<CXXOperatorCallExpr>(E) && Func->hasImplicitThisPointer());
6341 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
6342 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6343
6344 if (!this->emitCallVirt(Func, VarArgSize, E))
6345 return false;
6346 } else if (Func->isVariadic()) {
6347 uint32_t VarArgSize = 0;
6348 unsigned NumParams =
6349 Func->getNumWrittenParams() +
6350 (isa<CXXOperatorCallExpr>(E) && Func->hasImplicitThisPointer());
6351 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
6352 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6353 if (!this->emitCallVar(Func, VarArgSize, E))
6354 return false;
6355 } else {
6356 if (!this->emitCall(Func, 0, E))
6357 return false;
6358 }
6359 } else {
6360 // Indirect call. Visit the callee, which will leave a FunctionPointer on
6361 // the stack. Cleanup of the returned value if necessary will be done after
6362 // the function call completed.
6363
6364 // Sum the size of all args from the call expr.
6365 uint32_t ArgSize = 0;
6366 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
6367 ArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6368
6369 // Get the callee, either from a member pointer or function pointer saved in
6370 // CalleeOffset.
6371 if (isa<CXXMemberCallExpr>(E) && CalleeOffset) {
6372 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
6373 return false;
6374 if (!this->emitGetMemberPtrDecl(E))
6375 return false;
6376 } else {
6377 if (!this->emitGetLocal(PT_Ptr, *CalleeOffset, E))
6378 return false;
6379 }
6380 if (!this->emitCallPtr(ArgSize, E, E))
6381 return false;
6382 }
6383
6384 // Cleanup for discarded return values.
6385 if (DiscardResult && !ReturnType->isVoidType() && T)
6386 return this->emitPop(*T, E) && CallScope.destroyLocals();
6387
6388 return CallScope.destroyLocals();
6389}
6390
6391template <class Emitter>
6393 SourceLocScope<Emitter> SLS(this, E);
6394
6395 return this->delegate(E->getExpr());
6396}
6397
6398template <class Emitter>
6400 SourceLocScope<Emitter> SLS(this, E);
6401
6402 return this->delegate(E->getExpr());
6403}
6404
6405template <class Emitter>
6407 if (DiscardResult)
6408 return true;
6409
6410 return this->emitConstBool(E->getValue(), E);
6411}
6412
6413template <class Emitter>
6415 const CXXNullPtrLiteralExpr *E) {
6416 if (DiscardResult)
6417 return true;
6418
6419 uint64_t Val = Ctx.getASTContext().getTargetNullPointerValue(E->getType());
6420 return this->emitNullPtr(Val, nullptr, E);
6421}
6422
6423template <class Emitter>
6425 if (DiscardResult)
6426 return true;
6427
6428 assert(E->getType()->isIntegerType());
6429
6431 return this->emitZero(T, E);
6432}
6433
6434template <class Emitter>
6436 if (DiscardResult)
6437 return true;
6438
6439 if constexpr (!std::is_same_v<Emitter, EvalEmitter>) {
6440 if (this->LambdaThisCapture.Offset > 0) {
6441 if (this->LambdaThisCapture.IsPtr)
6442 return this->emitGetThisFieldPtr(this->LambdaThisCapture.Offset, E);
6443 return this->emitGetPtrThisField(this->LambdaThisCapture.Offset, E);
6444 }
6445 }
6446
6447 // In some circumstances, the 'this' pointer does not actually refer to the
6448 // instance pointer of the current function frame, but e.g. to the declaration
6449 // currently being initialized. Here we emit the necessary instruction(s) for
6450 // this scenario.
6451 if (!InitStackActive || InitStack.empty())
6452 return this->emitThis(E);
6453
6454 // If our init stack is, for example:
6455 // 0 Stack: 3 (decl)
6456 // 1 Stack: 6 (init list)
6457 // 2 Stack: 1 (field)
6458 // 3 Stack: 6 (init list)
6459 // 4 Stack: 1 (field)
6460 //
6461 // We want to find the LAST element in it that's an init list,
6462 // which is marked with the K_InitList marker. The index right
6463 // before that points to an init list. We need to find the
6464 // elements before the K_InitList element that point to a base
6465 // (e.g. a decl or This), optionally followed by field, elem, etc.
6466 // In the example above, we want to emit elements [0..2].
6467 unsigned StartIndex = 0;
6468 unsigned EndIndex = 0;
6469 // Find the init list.
6470 for (StartIndex = InitStack.size() - 1; StartIndex > 0; --StartIndex) {
6471 if (InitStack[StartIndex].Kind == InitLink::K_DIE) {
6472 EndIndex = StartIndex;
6473 --StartIndex;
6474 break;
6475 }
6476 }
6477
6478 // Walk backwards to find the base.
6479 for (; StartIndex > 0; --StartIndex) {
6480 if (InitStack[StartIndex].Kind == InitLink::K_InitList)
6481 continue;
6482
6483 if (InitStack[StartIndex].Kind != InitLink::K_Field &&
6484 InitStack[StartIndex].Kind != InitLink::K_Elem &&
6485 InitStack[StartIndex].Kind != InitLink::K_Base &&
6486 InitStack[StartIndex].Kind != InitLink::K_DIE)
6487 break;
6488 }
6489
6490 if (StartIndex == 0 && EndIndex == 0)
6491 EndIndex = InitStack.size() - 1;
6492
6493 assert(InitStack[StartIndex].Kind == InitLink::K_Decl ||
6494 InitStack[StartIndex].Kind == InitLink::K_This ||
6495 InitStack[StartIndex].Kind == InitLink::K_Temp ||
6496 InitStack[StartIndex].Kind == InitLink::K_RVO);
6497
6498 // NOTE: This could be StartIndex < EndIndex, but we're also abusing the
6499 // InitStack mechanism in visitWithSubstitutions to have the This pointer
6500 // _just_ be a local variable.
6501 assert(StartIndex <= EndIndex);
6502
6503 // Emit the instructions.
6504 for (unsigned I = StartIndex; I != (EndIndex + 1); ++I) {
6505 if (InitStack[I].Kind == InitLink::K_InitList ||
6506 InitStack[I].Kind == InitLink::K_DIE)
6507 continue;
6508 if (!InitStack[I].template emit<Emitter>(this, E))
6509 return false;
6510 }
6511 return true;
6512}
6513
6514template <class Emitter> bool Compiler<Emitter>::visitStmt(const Stmt *S) {
6515 switch (S->getStmtClass()) {
6516 case Stmt::CompoundStmtClass:
6518 case Stmt::DeclStmtClass:
6519 return visitDeclStmt(cast<DeclStmt>(S), /*EvaluateConditionDecl=*/true);
6520 case Stmt::ReturnStmtClass:
6522 case Stmt::IfStmtClass:
6523 return visitIfStmt(cast<IfStmt>(S));
6524 case Stmt::WhileStmtClass:
6526 case Stmt::DoStmtClass:
6527 return visitDoStmt(cast<DoStmt>(S));
6528 case Stmt::ForStmtClass:
6529 return visitForStmt(cast<ForStmt>(S));
6530 case Stmt::CXXForRangeStmtClass:
6532 case Stmt::BreakStmtClass:
6534 case Stmt::ContinueStmtClass:
6536 case Stmt::SwitchStmtClass:
6538 case Stmt::CaseStmtClass:
6539 return visitCaseStmt(cast<CaseStmt>(S));
6540 case Stmt::DefaultStmtClass:
6542 case Stmt::AttributedStmtClass:
6544 case Stmt::CXXTryStmtClass:
6546 case Stmt::NullStmtClass:
6547 return true;
6548 // Always invalid statements.
6549 case Stmt::GCCAsmStmtClass:
6550 case Stmt::MSAsmStmtClass:
6551 case Stmt::GotoStmtClass:
6552 return this->emitInvalid(S);
6553 case Stmt::LabelStmtClass:
6554 return this->visitStmt(cast<LabelStmt>(S)->getSubStmt());
6555 case Stmt::CXXExpansionStmtInstantiationClass:
6558 default: {
6559 if (const auto *E = dyn_cast<Expr>(S))
6560 return this->discard(E);
6561 return false;
6562 }
6563 }
6564}
6565
6566template <class Emitter>
6569 for (const auto *InnerStmt : S->body())
6570 if (!visitStmt(InnerStmt))
6571 return false;
6572 return Scope.destroyLocals();
6573}
6574
6575template <class Emitter>
6576bool Compiler<Emitter>::maybeEmitDeferredVarInit(const VarDecl *VD) {
6577 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
6578 for (auto *BD : DD->flat_bindings())
6579 if (auto *KD = BD->getHoldingVar();
6580 KD && !this->visitVarDecl(KD, KD->getInit()))
6581 return false;
6582 }
6583 return true;
6584}
6585
6587 assert(FD);
6588 assert(FD->getParent()->isUnion());
6589 const CXXRecordDecl *CXXRD =
6591 return !CXXRD || CXXRD->hasTrivialDefaultConstructor();
6592}
6593
6594template <class Emitter> bool Compiler<Emitter>::refersToUnion(const Expr *E) {
6595 for (;;) {
6596 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
6597 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6598 FD && FD->getParent()->isUnion() && hasTrivialDefaultCtorParent(FD))
6599 return true;
6600 E = ME->getBase();
6601 continue;
6602 }
6603
6604 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6605 E = ASE->getBase()->IgnoreImplicit();
6606 continue;
6607 }
6608
6609 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
6610 ICE && (ICE->getCastKind() == CK_NoOp ||
6611 ICE->getCastKind() == CK_DerivedToBase ||
6612 ICE->getCastKind() == CK_UncheckedDerivedToBase)) {
6613 E = ICE->getSubExpr();
6614 continue;
6615 }
6616
6617 if (const auto *This = dyn_cast<CXXThisExpr>(E)) {
6618 const auto *ThisRecord =
6619 This->getType()->getPointeeType()->getAsRecordDecl();
6620 if (!ThisRecord->isUnion())
6621 return false;
6622 // Otherwise, always activate if we're in the ctor.
6623 if (const auto *Ctor =
6624 dyn_cast_if_present<CXXConstructorDecl>(CompilingFunction))
6625 return Ctor->getParent() == ThisRecord;
6626 return false;
6627 }
6628
6629 break;
6630 }
6631 return false;
6632}
6633
6634template <class Emitter>
6636 bool EvaluateConditionDecl) {
6637 for (const auto *D : DS->decls()) {
6640 continue;
6641
6642 if (const auto *ESD = dyn_cast<CXXExpansionStmtDecl>(D)) {
6643 assert(ESD->getInstantiations() && "not expanded?");
6644 if (!this->visitStmt(ESD->getInstantiations()))
6645 return false;
6646 continue;
6647 }
6648
6649 const auto *VD = dyn_cast<VarDecl>(D);
6650 if (!VD)
6651 return false;
6652 if (!this->visitVarDecl(VD, VD->getInit()))
6653 return false;
6654
6655 // Register decomposition decl holding vars.
6656 if (EvaluateConditionDecl && !this->maybeEmitDeferredVarInit(VD))
6657 return false;
6658 }
6659
6660 return true;
6661}
6662
6663template <class Emitter>
6665 if (this->InStmtExpr)
6666 return this->emitUnsupported(RS);
6667
6668 if (const Expr *RE = RS->getRetValue()) {
6669 LocalScope<Emitter> RetScope(this);
6670 if (ReturnType) {
6671 // Primitive types are simply returned.
6672 if (!this->visit(RE))
6673 return false;
6674 this->emitCleanup();
6675 return this->emitRet(*ReturnType, RS);
6676 }
6677
6678 if (RE->getType()->isVoidType()) {
6679 if (!this->visit(RE))
6680 return false;
6681 } else {
6682 if (RE->containsErrors())
6683 return false;
6684
6686 // RVO - construct the value in the return location.
6687 if (!this->emitRVOPtr(RE))
6688 return false;
6689 if (!this->visitInitializerPop(RE))
6690 return false;
6691
6692 this->emitCleanup();
6693 return this->emitRetVoid(RS);
6694 }
6695 }
6696
6697 // Void return.
6698 this->emitCleanup();
6699 return this->emitRetVoid(RS);
6700}
6701
6702template <class Emitter> bool Compiler<Emitter>::visitIfStmt(const IfStmt *IS) {
6703 LocalScope<Emitter> IfScope(this);
6704
6705 auto visitChildStmt = [&](const Stmt *S) -> bool {
6706 LocalScope<Emitter> SScope(this);
6707 if (!visitStmt(S))
6708 return false;
6709 return SScope.destroyLocals();
6710 };
6711
6712 if (auto *CondInit = IS->getInit()) {
6713 if (!visitStmt(CondInit))
6714 return false;
6715 }
6716
6717 if (const DeclStmt *CondDecl = IS->getConditionVariableDeclStmt()) {
6718 if (!visitDeclStmt(CondDecl))
6719 return false;
6720 }
6721
6722 // Save ourselves compiling some code and the jumps, etc. if the condition is
6723 // stataically known to be either true or false. We could look at more cases
6724 // here, but I think all the ones that actually happen are using a
6725 // ConstantExpr.
6726 if (std::optional<bool> BoolValue = getBoolValue(IS->getCond())) {
6727 if (*BoolValue)
6728 return visitChildStmt(IS->getThen());
6729 if (const Stmt *Else = IS->getElse())
6730 return visitChildStmt(Else);
6731 return true;
6732 }
6733
6734 // Otherwise, compile the condition.
6735 if (IS->isNonNegatedConsteval()) {
6736 if (!this->emitIsConstantContext(IS))
6737 return false;
6738 } else if (IS->isNegatedConsteval()) {
6739 if (!this->emitIsConstantContext(IS))
6740 return false;
6741 if (!this->emitInv(IS))
6742 return false;
6743 } else {
6745 if (!this->visitBool(IS->getCond()))
6746 return false;
6747 if (!CondScope.destroyLocals())
6748 return false;
6749 }
6750
6751 if (!this->maybeEmitDeferredVarInit(IS->getConditionVariable()))
6752 return false;
6753
6754 if (const Stmt *Else = IS->getElse()) {
6755 LabelTy LabelElse = this->getLabel();
6756 LabelTy LabelEnd = this->getLabel();
6757 if (!this->jumpFalse(LabelElse, IS))
6758 return false;
6759 if (!visitChildStmt(IS->getThen()))
6760 return false;
6761 if (!this->jump(LabelEnd, IS))
6762 return false;
6763 this->emitLabel(LabelElse);
6764 if (!visitChildStmt(Else))
6765 return false;
6766 this->emitLabel(LabelEnd);
6767 } else {
6768 LabelTy LabelEnd = this->getLabel();
6769 if (!this->jumpFalse(LabelEnd, IS))
6770 return false;
6771 if (!visitChildStmt(IS->getThen()))
6772 return false;
6773 this->emitLabel(LabelEnd);
6774 }
6775
6776 if (!IfScope.destroyLocals())
6777 return false;
6778
6779 return true;
6780}
6781
6782template <class Emitter>
6784 const Expr *Cond = S->getCond();
6785 const Stmt *Body = S->getBody();
6786
6787 LabelTy CondLabel = this->getLabel(); // Label before the condition.
6788 LabelTy EndLabel = this->getLabel(); // Label after the loop.
6789 LocalScope<Emitter> WholeLoopScope(this);
6790 LoopScope<Emitter> LS(this, S, EndLabel, CondLabel);
6791
6792 this->fallthrough(CondLabel);
6793 this->emitLabel(CondLabel);
6794
6795 // Start of the loop body {
6796 LocalScope<Emitter> CondScope(this);
6797
6798 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) {
6799 if (!visitDeclStmt(CondDecl))
6800 return false;
6801 }
6802
6803 if (!this->visitBool(Cond))
6804 return false;
6805
6806 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
6807 return false;
6808
6809 if (!this->jumpFalse(EndLabel, S))
6810 return false;
6811
6812 if (!this->visitStmt(Body))
6813 return false;
6814
6815 if (!CondScope.destroyLocals())
6816 return false;
6817 // } End of loop body.
6818
6819 if (!this->jump(CondLabel, S))
6820 return false;
6821 this->fallthrough(EndLabel);
6822 this->emitLabel(EndLabel);
6823
6824 return CondScope.destroyLocals() && WholeLoopScope.destroyLocals();
6825}
6826
6827template <class Emitter> bool Compiler<Emitter>::visitDoStmt(const DoStmt *S) {
6828 const Expr *Cond = S->getCond();
6829 const Stmt *Body = S->getBody();
6830
6831 LabelTy StartLabel = this->getLabel();
6832 LabelTy EndLabel = this->getLabel();
6833 LabelTy CondLabel = this->getLabel();
6834 LocalScope<Emitter> WholeLoopScope(this);
6835 LoopScope<Emitter> LS(this, S, EndLabel, CondLabel);
6836
6837 this->fallthrough(StartLabel);
6838 this->emitLabel(StartLabel);
6839
6840 {
6841 LocalScope<Emitter> CondScope(this);
6842 if (!this->visitStmt(Body))
6843 return false;
6844 this->fallthrough(CondLabel);
6845 this->emitLabel(CondLabel);
6846 if (!this->visitBool(Cond))
6847 return false;
6848
6849 if (!CondScope.destroyLocals())
6850 return false;
6851 }
6852 if (!this->jumpTrue(StartLabel, S))
6853 return false;
6854
6855 this->fallthrough(EndLabel);
6856 this->emitLabel(EndLabel);
6857 return WholeLoopScope.destroyLocals();
6858}
6859
6860template <class Emitter>
6862 // for (Init; Cond; Inc) { Body }
6863 const Stmt *Init = S->getInit();
6864 const Expr *Cond = S->getCond();
6865 const Expr *Inc = S->getInc();
6866 const Stmt *Body = S->getBody();
6867
6868 LabelTy EndLabel = this->getLabel();
6869 LabelTy CondLabel = this->getLabel();
6870 LabelTy IncLabel = this->getLabel();
6871
6872 LocalScope<Emitter> WholeLoopScope(this);
6873 if (Init && !this->visitStmt(Init))
6874 return false;
6875
6876 // Start of the loop body {
6877 this->fallthrough(CondLabel);
6878 this->emitLabel(CondLabel);
6879
6880 LocalScope<Emitter> CondScope(this);
6881 LoopScope<Emitter> LS(this, S, EndLabel, IncLabel);
6882 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) {
6883 if (!visitDeclStmt(CondDecl))
6884 return false;
6885 }
6886
6887 if (Cond) {
6888 if (!this->visitBool(Cond))
6889 return false;
6890 if (!this->jumpFalse(EndLabel, S))
6891 return false;
6892 }
6893 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
6894 return false;
6895
6896 if (Body && !this->visitStmt(Body))
6897 return false;
6898
6899 this->fallthrough(IncLabel);
6900 this->emitLabel(IncLabel);
6901 if (Inc && !this->discard(Inc))
6902 return false;
6903
6904 if (!CondScope.destroyLocals())
6905 return false;
6906 if (!this->jump(CondLabel, S))
6907 return false;
6908 // } End of loop body.
6909
6910 this->emitLabel(EndLabel);
6911 // If we jumped out of the loop above, we still need to clean up the condition
6912 // scope.
6913 return CondScope.destroyLocals() && WholeLoopScope.destroyLocals();
6914}
6915
6916template <class Emitter>
6918 const Stmt *Init = S->getInit();
6919 const Expr *Cond = S->getCond();
6920 const Expr *Inc = S->getInc();
6921 const Stmt *Body = S->getBody();
6922 const Stmt *BeginStmt = S->getBeginStmt();
6923 const Stmt *RangeStmt = S->getRangeStmt();
6924 const Stmt *EndStmt = S->getEndStmt();
6925
6926 LabelTy EndLabel = this->getLabel();
6927 LabelTy CondLabel = this->getLabel();
6928 LabelTy IncLabel = this->getLabel();
6929 LocalScope<Emitter> WholeLoopScope(this);
6930 LoopScope<Emitter> LS(this, S, EndLabel, IncLabel);
6931
6932 // Emit declarations needed in the loop.
6933 if (Init && !this->visitStmt(Init))
6934 return false;
6935 if (!this->visitStmt(RangeStmt))
6936 return false;
6937 if (!this->visitStmt(BeginStmt))
6938 return false;
6939 if (!this->visitStmt(EndStmt))
6940 return false;
6941
6942 LocalScope<Emitter> CondScope(this);
6943 // Now the condition as well as the loop variable assignment.
6944 this->fallthrough(CondLabel);
6945 this->emitLabel(CondLabel);
6946 if (!this->visitBool(Cond))
6947 return false;
6948 if (!this->jumpFalse(EndLabel, S))
6949 return false;
6950
6951 if (!this->visitDeclStmt(S->getLoopVarStmt(), /*EvaluateConditionDecl=*/true))
6952 return false;
6953
6954 // Body.
6955 {
6956 if (!this->visitStmt(Body))
6957 return false;
6958
6959 this->fallthrough(IncLabel);
6960 this->emitLabel(IncLabel);
6961 if (!this->discard(Inc))
6962 return false;
6963 }
6964
6965 if (!CondScope.destroyLocals())
6966 return false;
6967 if (!this->jump(CondLabel, S))
6968 return false;
6969
6970 this->fallthrough(EndLabel);
6971 this->emitLabel(EndLabel);
6972 return WholeLoopScope.destroyLocals();
6973}
6974
6975template <class Emitter>
6977 if (LabelInfoStack.empty())
6978 return false;
6979
6980 OptLabelTy TargetLabel = std::nullopt;
6981 const Stmt *TargetLoop = S->getNamedLoopOrSwitch();
6982 const VariableScope<Emitter> *BreakScope = nullptr;
6983
6984 if (!TargetLoop) {
6985 for (const auto &LI : llvm::reverse(LabelInfoStack)) {
6986 if (LI.BreakLabel) {
6987 TargetLabel = *LI.BreakLabel;
6988 BreakScope = LI.BreakOrContinueScope;
6989 break;
6990 }
6991 }
6992 } else {
6993 for (const auto &LI : LabelInfoStack) {
6994 if (LI.Name == TargetLoop) {
6995 TargetLabel = *LI.BreakLabel;
6996 BreakScope = LI.BreakOrContinueScope;
6997 break;
6998 }
6999 }
7000 }
7001
7002 // Faulty break statement (e.g. label redefined or named loops disabled).
7003 if (!TargetLabel)
7004 return false;
7005
7006 for (VariableScope<Emitter> *C = this->VarScope; C != BreakScope;
7007 C = C->getParent()) {
7008 if (!C->destroyLocals())
7009 return false;
7010 }
7011
7012 return this->jump(*TargetLabel, S);
7013}
7014
7015template <class Emitter>
7017 if (LabelInfoStack.empty())
7018 return false;
7019
7020 OptLabelTy TargetLabel = std::nullopt;
7021 const Stmt *TargetLoop = S->getNamedLoopOrSwitch();
7022 const VariableScope<Emitter> *ContinueScope = nullptr;
7023
7024 if (!TargetLoop) {
7025 for (const auto &LI : llvm::reverse(LabelInfoStack)) {
7026 if (LI.ContinueLabel) {
7027 TargetLabel = *LI.ContinueLabel;
7028 ContinueScope = LI.BreakOrContinueScope;
7029 break;
7030 }
7031 }
7032 } else {
7033 for (auto LI : LabelInfoStack) {
7034 if (LI.Name == TargetLoop) {
7035 TargetLabel = *LI.ContinueLabel;
7036 ContinueScope = LI.BreakOrContinueScope;
7037 break;
7038 }
7039 }
7040 }
7041
7042 if (!TargetLabel)
7043 return false;
7044
7045 for (VariableScope<Emitter> *C = VarScope; C != ContinueScope;
7046 C = C->getParent()) {
7047 if (!C->destroyLocals())
7048 return false;
7049 }
7050
7051 return this->jump(*TargetLabel, S);
7052}
7053
7054template <class Emitter>
7056 const Expr *Cond = S->getCond();
7057 if (Cond->containsErrors())
7058 return false;
7059
7060 PrimType CondT = this->classifyPrim(Cond->getType());
7061 LocalScope<Emitter> LS(this);
7062 llvm::SaveAndRestore StmtExprSAR(this->SwitchInStmtExpr, this->InStmtExpr);
7063
7064 LabelTy EndLabel = this->getLabel();
7065 UnsignedOrNone DefaultLabel = std::nullopt;
7066 unsigned CondVar =
7067 this->allocateLocalPrimitive(Cond, CondT, /*IsConst=*/true);
7068
7069 if (const auto *CondInit = S->getInit())
7070 if (!visitStmt(CondInit))
7071 return false;
7072
7073 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
7074 if (!visitDeclStmt(CondDecl))
7075 return false;
7076
7077 // Initialize condition variable.
7078 if (!this->visit(Cond))
7079 return false;
7080 if (!this->emitSetLocal(CondT, CondVar, S))
7081 return false;
7082
7083 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
7084 return false;
7085
7087 // Create labels and comparison ops for all case statements.
7088 for (const SwitchCase *SC = S->getSwitchCaseList(); SC;
7089 SC = SC->getNextSwitchCase()) {
7090 if (const auto *CS = dyn_cast<CaseStmt>(SC)) {
7091 CaseLabels[SC] = this->getLabel();
7092
7093 if (CS->caseStmtIsGNURange()) {
7094 LabelTy EndOfRangeCheck = this->getLabel();
7095 const Expr *Low = CS->getLHS();
7096 const Expr *High = CS->getRHS();
7097 if (Low->isValueDependent() || High->isValueDependent())
7098 return false;
7099
7100 if (!this->emitGetLocal(CondT, CondVar, CS))
7101 return false;
7102 if (!this->visit(Low))
7103 return false;
7104 PrimType LT = this->classifyPrim(Low->getType());
7105 if (!this->emitGE(LT, S))
7106 return false;
7107 if (!this->jumpFalse(EndOfRangeCheck, S))
7108 return false;
7109
7110 if (!this->emitGetLocal(CondT, CondVar, CS))
7111 return false;
7112 if (!this->visit(High))
7113 return false;
7114 PrimType HT = this->classifyPrim(High->getType());
7115 if (!this->emitLE(HT, S))
7116 return false;
7117 if (!this->jumpTrue(CaseLabels[CS], S))
7118 return false;
7119 this->emitLabel(EndOfRangeCheck);
7120 continue;
7121 }
7122
7123 const Expr *Value = CS->getLHS();
7124 if (Value->isValueDependent())
7125 return false;
7126 PrimType ValueT = this->classifyPrim(Value->getType());
7127
7128 // Compare the case statement's value to the switch condition.
7129 if (!this->emitGetLocal(CondT, CondVar, CS))
7130 return false;
7131 if (!this->visit(Value))
7132 return false;
7133
7134 // Compare and jump to the case label.
7135 if (!this->emitEQ(ValueT, S))
7136 return false;
7137 if (!this->jumpTrue(CaseLabels[CS], S))
7138 return false;
7139 } else {
7140 assert(!DefaultLabel);
7141 DefaultLabel = this->getLabel();
7142 }
7143 }
7144
7145 // If none of the conditions above were true, fall through to the default
7146 // statement or jump after the switch statement.
7147 if (DefaultLabel) {
7148 if (!this->jump(*DefaultLabel, S))
7149 return false;
7150 } else {
7151 if (!this->jump(EndLabel, S))
7152 return false;
7153 }
7154
7155 SwitchScope<Emitter> SS(this, S, std::move(CaseLabels), EndLabel,
7156 DefaultLabel);
7157 if (!this->visitStmt(S->getBody()))
7158 return false;
7159 this->fallthrough(EndLabel);
7160 this->emitLabel(EndLabel);
7161
7162 return LS.destroyLocals();
7163}
7164
7165template <class Emitter>
7167 this->fallthrough(CaseLabels[S]);
7168 this->emitLabel(CaseLabels[S]);
7169
7170 // We can't jump from an outer switch statement to a case label
7171 // that's inside a StmtExpr.
7172 if (this->InStmtExpr && !this->SwitchInStmtExpr)
7173 return this->emitUnsupported(S);
7174
7175 return this->visitStmt(S->getSubStmt());
7176}
7177
7178template <class Emitter>
7180 if (LabelInfoStack.empty())
7181 return false;
7182
7183 LabelTy DefaultLabel;
7184 for (const LabelInfo &LI : llvm::reverse(LabelInfoStack)) {
7185 if (LI.DefaultLabel) {
7186 DefaultLabel = *LI.DefaultLabel;
7187 break;
7188 }
7189 }
7190
7191 this->emitLabel(DefaultLabel);
7192 return this->visitStmt(S->getSubStmt());
7193}
7194
7195template <class Emitter>
7197 const Stmt *SubStmt = S->getSubStmt();
7198
7199 bool IsMSVCConstexprAttr = isa<ReturnStmt>(SubStmt) &&
7201
7202 if (IsMSVCConstexprAttr && !this->emitPushMSVCCE(S))
7203 return false;
7204
7205 if (this->Ctx.getLangOpts().CXXAssumptions &&
7206 !this->Ctx.getLangOpts().MSVCCompat) {
7207 for (const Attr *A : S->getAttrs()) {
7208 auto *AA = dyn_cast<CXXAssumeAttr>(A);
7209 if (!AA)
7210 continue;
7211
7212 assert(isa<NullStmt>(SubStmt));
7213
7214 const Expr *Assumption = AA->getAssumption();
7215 if (Assumption->isValueDependent())
7216 return false;
7217
7218 if (Assumption->HasSideEffects(this->Ctx.getASTContext()))
7219 continue;
7220
7221 // Evaluate assumption.
7222 if (!this->visitBool(Assumption))
7223 return false;
7224
7225 if (!this->emitAssume(Assumption))
7226 return false;
7227 }
7228 }
7229
7230 // Ignore other attributes.
7231 if (!this->visitStmt(SubStmt))
7232 return false;
7233
7234 if (IsMSVCConstexprAttr)
7235 return this->emitPopMSVCCE(S);
7236 return true;
7237}
7238
7239template <class Emitter>
7241 // Ignore all handlers.
7242 return this->visitStmt(S->getTryBlock());
7243}
7244
7245/// template for (auto x : {1, 2}) {}
7246///
7247/// This is not a loop from an AST perspective at all since it has already
7248/// been instantiated to a list of compound statements.
7249///
7250/// Since we can have control flow in those compound statements, we need to
7251/// handle it mostly like a loop though.
7252template <class Emitter>
7255 LocalScope<Emitter> WholeLoopScope(this, ScopeKind::Block);
7256
7257 for (const Stmt *PreambleStmt : S->getPreambleStmts()) {
7258 if (!this->visitDeclStmt(cast<DeclStmt>(PreambleStmt), true))
7259 return false;
7260 }
7261
7262 LabelTy EndLabel = this->getLabel();
7263 for (const Stmt *Instantiation : S->getInstantiations()) {
7264 LabelTy ContinueLabel = this->getLabel();
7265 LoopScope<Emitter> LS(this, S, EndLabel, ContinueLabel);
7266
7267 if (!this->visitStmt(Instantiation))
7268 return false;
7269 this->emitLabel(ContinueLabel);
7270 }
7271
7272 this->emitLabel(EndLabel);
7273
7274 return WholeLoopScope.destroyLocals();
7275}
7276
7277template <class Emitter>
7278bool Compiler<Emitter>::emitLambdaStaticInvokerBody(const CXXMethodDecl *MD) {
7279 assert(MD->isLambdaStaticInvoker());
7280 assert(MD->hasBody());
7281 assert(cast<CompoundStmt>(MD->getBody())->body_empty());
7282
7283 const CXXRecordDecl *ClosureClass = MD->getParent();
7284 const FunctionDecl *LambdaCallOp;
7285 assert(ClosureClass->captures().empty());
7286 if (ClosureClass->isGenericLambda()) {
7287 LambdaCallOp = ClosureClass->getLambdaCallOperator();
7288 assert(MD->isFunctionTemplateSpecialization() &&
7289 "A generic lambda's static-invoker function must be a "
7290 "template specialization");
7292 FunctionTemplateDecl *CallOpTemplate =
7293 LambdaCallOp->getDescribedFunctionTemplate();
7294 llvm::FoldingSetInsertToken InsertToken;
7295 const FunctionDecl *CorrespondingCallOpSpecialization =
7296 CallOpTemplate->findSpecialization(TAL->asArray(), InsertToken);
7297 assert(CorrespondingCallOpSpecialization);
7298 LambdaCallOp = CorrespondingCallOpSpecialization;
7299 } else {
7300 LambdaCallOp = ClosureClass->getLambdaCallOperator();
7301 }
7302 assert(ClosureClass->captures().empty());
7303 const Function *Func = this->getFunction(LambdaCallOp);
7304 if (!Func)
7305 return false;
7306 assert(Func->hasThisPointer());
7307 assert(Func->getNumParams() == (MD->getNumParams() + 1 + Func->hasRVO()));
7308
7309 if (Func->hasRVO()) {
7310 if (!this->emitRVOPtr(MD))
7311 return false;
7312 }
7313
7314 // The lambda call operator needs an instance pointer, but we don't have
7315 // one here, and we don't need one either because the lambda cannot have
7316 // any captures, as verified above. Emit a null pointer. This is then
7317 // special-cased when interpreting to not emit any misleading diagnostics.
7318 if (!this->emitNullPtr(0, nullptr, MD))
7319 return false;
7320
7321 // Forward all arguments from the static invoker to the lambda call operator.
7322 for (const ParmVarDecl *PVD : MD->parameters()) {
7323 auto It = this->Params.find(PVD);
7324 assert(It != this->Params.end());
7325
7326 // We do the lvalue-to-rvalue conversion manually here, so no need
7327 // to care about references.
7328 PrimType ParamType = this->classify(PVD->getType()).value_or(PT_Ptr);
7329 if (!this->emitGetParam(ParamType, It->second.Index, MD))
7330 return false;
7331 }
7332
7333 if (!this->emitCall(Func, 0, LambdaCallOp))
7334 return false;
7335
7336 this->emitCleanup();
7337 if (ReturnType)
7338 return this->emitRet(*ReturnType, MD);
7339
7340 // Nothing to do, since we emitted the RVO pointer above.
7341 return this->emitRetVoid(MD);
7342}
7343
7344template <class Emitter>
7345bool Compiler<Emitter>::checkLiteralType(const Expr *E) {
7346 if (Ctx.getLangOpts().CPlusPlus23)
7347 return true;
7348
7349 if (!E->isPRValue() || E->getType()->isLiteralType(Ctx.getASTContext()))
7350 return true;
7351
7352 return this->emitCheckLiteralType(E->getType().getTypePtr(), E);
7353}
7354
7356 const Expr *InitExpr = Init->getInit();
7357
7358 if (!Init->isWritten() && !Init->isInClassMemberInitializer() &&
7359 !isa<CXXConstructExpr>(InitExpr))
7360 return true;
7361
7362 if (const auto *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
7363 const CXXConstructorDecl *Ctor = CE->getConstructor();
7364 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
7365 Ctor->isTrivial())
7366 return true;
7367 }
7368
7369 return false;
7370}
7371
7372template <class Emitter>
7373bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
7374 assert(!ReturnType);
7375
7376 // Only start the lifetime of the instance pointer.
7377 if (!this->emitStartThisLifetime1(Ctor))
7378 return false;
7379
7380 auto emitFieldInitializer = [&](const Record::Field *F, unsigned FieldOffset,
7381 const Expr *InitExpr,
7382 bool Activate = false) -> bool {
7383 // We don't know what to do with these, so just return false.
7384 if (InitExpr->getType().isNull())
7385 return false;
7386
7387 if (OptPrimType T = this->classify(InitExpr)) {
7388 if (Activate && !this->emitActivateThisField(FieldOffset, InitExpr))
7389 return false;
7390
7391 if (!this->visit(InitExpr))
7392 return false;
7393
7394 if (F->isBitField())
7395 return this->emitInitThisBitField(*T, FieldOffset, F->bitWidth(),
7396 InitExpr);
7397 return this->emitInitThisField(*T, FieldOffset, InitExpr);
7398 }
7399 // Non-primitive case. Get a pointer to the field-to-initialize
7400 // on the stack and call visitInitialzer() for it.
7401 InitLinkScope<Emitter> FieldScope(this, InitLink::Field(F->Offset));
7402 if (!this->emitGetPtrThisField(FieldOffset, InitExpr))
7403 return false;
7404
7405 if (Activate && !this->emitActivate(InitExpr))
7406 return false;
7407
7408 return this->visitInitializerPop(InitExpr);
7409 };
7410
7411 const RecordDecl *RD = Ctor->getParent();
7412 const Record *R = this->getRecord(RD);
7413 if (!R)
7414 return false;
7415 bool IsUnion = R->isUnion();
7416
7417 // Default union copy and move ctors are special.
7418 if (IsUnion && Ctor->isCopyOrMoveConstructor() && Ctor->isDefaulted()) {
7420
7421 // No special case for NumFields == 0 here, so the Memcpy op
7422 // below also does its checks in those cases.
7423
7424 assert(cast<CompoundStmt>(Ctor->getBody())->body_empty());
7425 if (!this->emitThis(Ctor))
7426 return false;
7427
7428 if (!this->emitGetParam(PT_Ptr, /*ParamIndex=*/0, Ctor))
7429 return false;
7430
7431 return this->emitMemcpy(Ctor) && this->emitPopPtr(Ctor) &&
7432 this->emitRetVoid(Ctor);
7433 }
7434
7435 unsigned FieldInits = 0;
7437 // First, initialize virtual bases if the records has them.
7438 if (R->getNumVirtualBases() > 0) {
7439 if (!this->emitThis(Ctor))
7440 return false;
7441 LabelTy AfterVirtBasesLabel = this->getLabel();
7442
7443 // If the instance pointer is a base class, skip the virtual bases.
7444 if (!this->emitIsBaseClass({}))
7445 return false;
7446 if (!this->jumpTrue(AfterVirtBasesLabel, {}))
7447 return false;
7448
7449 for (const auto *Init : Ctor->inits()) {
7450 if (const Type *Base = Init->getBaseClass();
7451 Base && Init->isBaseVirtual()) {
7452 const auto *BaseDecl = Base->getAsCXXRecordDecl();
7453 assert(BaseDecl);
7454 assert(R->findVirtualBase(BaseDecl));
7455 if (!this->emitGetPtrThisVirtBase(BaseDecl, Ctor))
7456 return false;
7457 if (!this->visitInitializerPop(Init->getInit()))
7458 return false;
7459 }
7460 }
7461
7462 this->fallthrough(AfterVirtBasesLabel);
7463 this->emitLabel(AfterVirtBasesLabel);
7464
7465 if (!this->emitPopPtr(Ctor))
7466 return false;
7467 }
7468
7469 for (const auto *Init : Ctor->inits()) {
7470 // Scope needed for the initializers.
7471 LocalScope<Emitter> Scope(this, ScopeKind::FullExpression);
7472
7473 const Expr *InitExpr = Init->getInit();
7474 if (const FieldDecl *Member = Init->getMember()) {
7475 const Record::Field *F = R->getField(Member);
7476
7479 if (!emitFieldInitializer(F, F->Offset, InitExpr, IsUnion))
7480 return false;
7481 ++FieldInits;
7482 } else if (const Type *Base = Init->getBaseClass()) {
7483 const auto *BaseDecl = Base->getAsCXXRecordDecl();
7484 assert(BaseDecl);
7485
7486 if (Init->isBaseVirtual()) {
7487 // See above.
7488 continue;
7489 } else {
7490 // Base class initializer.
7491 // Get This Base and call initializer on it.
7492 const Record::Base *B = R->getBase(BaseDecl);
7493 assert(B);
7494 if (!this->emitGetPtrThisBase(B->Offset, InitExpr))
7495 return false;
7496 }
7497
7498 if (!this->visitInitializerPop(InitExpr))
7499 return false;
7500 } else if (const IndirectFieldDecl *IFD = Init->getIndirectMember()) {
7503 unsigned ChainSize = IFD->getChainingSize();
7504 assert(ChainSize >= 2);
7505
7506 unsigned NestedFieldOffset = 0;
7507 const Record::Field *NestedField = nullptr;
7508 for (unsigned I = 0; I != ChainSize; ++I) {
7509 const auto *FD = cast<FieldDecl>(IFD->chain()[I]);
7510 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
7511 assert(FieldRecord);
7512
7513 NestedField = FieldRecord->getField(FD);
7514 assert(NestedField);
7515 IsUnion = IsUnion || FieldRecord->isUnion();
7516
7517 NestedFieldOffset += NestedField->Offset;
7518
7519 // Add a new InitChainLink for the record, but not for the final field.
7520 if (I != ChainSize - 1)
7521 InitStack.push_back(InitLink::Field(NestedField->Offset));
7522 }
7523 assert(NestedField);
7524
7526 if (!emitFieldInitializer(NestedField, NestedFieldOffset, InitExpr,
7527 IsUnion))
7528 return false;
7529
7530 // Mark all chain links as initialized.
7531 unsigned InitFieldOffset = 0;
7532 for (const NamedDecl *ND : IFD->chain().drop_back()) {
7533 const auto *FD = cast<FieldDecl>(ND);
7534 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
7535 assert(FieldRecord);
7536 NestedField = FieldRecord->getField(FD);
7537 InitFieldOffset += NestedField->Offset;
7538 assert(NestedField);
7539 if (!this->emitGetPtrThisField(InitFieldOffset, InitExpr))
7540 return false;
7541 if (!this->emitFinishInitPop(InitExpr))
7542 return false;
7543 }
7544
7545 InitStack.pop_back_n(ChainSize - 1);
7546
7547 } else {
7548 assert(Init->isDelegatingInitializer());
7549 if (!this->emitThis(InitExpr))
7550 return false;
7551 if (!this->visitInitializerPop(Init->getInit()))
7552 return false;
7553 }
7554
7555 if (!Scope.destroyLocals())
7556 return false;
7557 }
7558
7559 if (FieldInits != R->getNumFields()) {
7560 assert(FieldInits < R->getNumFields());
7561 // Start the lifetime of all members.
7562 if (!this->emitStartThisLifetime(Ctor))
7563 return false;
7564 }
7565
7566 if (const Stmt *Body = Ctor->getBody()) {
7567 // Only emit the CtorCheck op for non-empty CompoundStmt bodies.
7568 // For non-CompoundStmts, always assume they are non-empty and emit it.
7569 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
7570 if (!CS->body_empty() && !this->emitCtorCheck(SourceInfo{}))
7571 return false;
7572 } else {
7573 if (!this->emitCtorCheck(SourceInfo{}))
7574 return false;
7575 }
7576
7577 if (!visitStmt(Body))
7578 return false;
7579 }
7580
7581 return this->emitRetVoid(SourceInfo{});
7582}
7583
7584template <class Emitter>
7585bool Compiler<Emitter>::compileDestructor(const CXXDestructorDecl *Dtor) {
7586 const RecordDecl *RD = Dtor->getParent();
7587 const Record *R = this->getRecord(RD);
7588 if (!R)
7589 return false;
7590
7591 if (!Dtor->isTrivial() && Dtor->getBody()) {
7592 if (!this->visitStmt(Dtor->getBody()))
7593 return false;
7594 }
7595
7596 if (!this->emitThis(Dtor))
7597 return false;
7598
7599 if (!this->emitCheckDestruction(Dtor))
7600 return false;
7601
7602 assert(R);
7603 if (!R->isUnion()) {
7604
7606 // First, destroy all fields.
7607 for (const Record::Field &Field : llvm::reverse(R->fields())) {
7608 const Descriptor *D = Field.Desc;
7609 if (D->hasTrivialDtor())
7610 continue;
7611 if (!this->emitGetPtrField(Field.Offset, SourceInfo{}))
7612 return false;
7613 if (!this->emitDestructionPop(D, SourceInfo{}))
7614 return false;
7615 }
7616 }
7617
7618 for (const Record::Base &Base : llvm::reverse(R->bases())) {
7619 if (Base.R->hasTrivialDtor())
7620 continue;
7621 if (!this->emitGetPtrBase(Base.Offset, SourceInfo{}))
7622 return false;
7623 if (!this->emitRecordDestructionPop(Base.R, {}))
7624 return false;
7625 }
7626
7627 if (R->getNumVirtualBases() > 0) {
7628 LabelTy EndLabel = this->getLabel();
7629 // If this is a base class, skip the virtual bases.
7630 if (!this->emitIsBaseClass({}))
7631 return false;
7632 if (!this->jumpTrue(EndLabel, {}))
7633 return false;
7634
7635 for (const Record::Base &Base : llvm::reverse(R->virtual_bases())) {
7636 if (Base.R->hasTrivialDtor())
7637 continue;
7638 if (!this->emitGetPtrVirtBase(cast<CXXRecordDecl>(Base.R->getDecl()),
7639 SourceInfo{}))
7640 return false;
7641 if (!this->emitRecordDestructionPop(Base.R, {}))
7642 return false;
7643 }
7644
7645 this->fallthrough(EndLabel);
7646 this->emitLabel(EndLabel);
7647 }
7648
7649 if (!this->emitMarkDestroyed(Dtor))
7650 return false;
7651
7652 return this->emitPopPtr(Dtor) && this->emitRetVoid(Dtor);
7653}
7654
7655template <class Emitter>
7656bool Compiler<Emitter>::compileUnionAssignmentOperator(
7657 const CXXMethodDecl *MD) {
7658 if (!this->emitThis(MD))
7659 return false;
7660
7661 if (!this->emitGetParam(PT_Ptr, /*ParamIndex=*/0, MD))
7662 return false;
7663
7664 return this->emitMemcpy(MD) && this->emitRet(PT_Ptr, MD);
7665}
7666
7667template <class Emitter>
7669 if (F->getReturnType()->isDependentType())
7670 return false;
7671
7672 // Classify the return type.
7673 ReturnType = this->classify(F->getReturnType());
7674
7675 this->CompilingFunction = F;
7676
7677 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(F))
7678 return this->compileConstructor(Ctor);
7679 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(F))
7680 return this->compileDestructor(Dtor);
7681
7682 // Emit custom code if this is a lambda static invoker.
7683 if (const auto *MD = dyn_cast<CXXMethodDecl>(F)) {
7684 const RecordDecl *RD = MD->getParent();
7685
7686 if (RD->isUnion() &&
7688 return this->compileUnionAssignmentOperator(MD);
7689
7690 if (MD->isLambdaStaticInvoker())
7691 return this->emitLambdaStaticInvokerBody(MD);
7692 }
7693
7694 // Regular functions.
7695 if (const auto *Body = F->getBody())
7696 if (!visitStmt(Body))
7697 return false;
7698
7699 // Emit a guard return to protect against a code path missing one.
7700 if (F->getReturnType()->isVoidType())
7701 return this->emitRetVoid(SourceInfo{});
7702 return this->emitNoRet(SourceInfo{});
7703}
7704
7705static uint32_t getBitWidth(const Expr *E) {
7706 assert(E->refersToBitField());
7707 const auto *ME = cast<MemberExpr>(E);
7708 const auto *FD = cast<FieldDecl>(ME->getMemberDecl());
7709 return FD->getBitWidthValue();
7710}
7711
7712template <class Emitter>
7714 if (E->containsErrors())
7715 return false;
7716
7717 const Expr *SubExpr = E->getSubExpr();
7718 if (SubExpr->getType()->isAnyComplexType())
7719 return this->VisitComplexUnaryOperator(E);
7720 if (SubExpr->getType()->isVectorType())
7721 return this->VisitVectorUnaryOperator(E);
7722 if (SubExpr->getType()->isFixedPointType())
7723 return this->VisitFixedPointUnaryOperator(E);
7724 OptPrimType T = classify(SubExpr->getType());
7725
7726 switch (E->getOpcode()) {
7727 case UO_PostInc: { // x++
7728 if (!Ctx.getLangOpts().CPlusPlus14)
7729 return this->emitInvalid(E);
7730 if (!T)
7731 return this->emitError(E);
7732
7733 if (!this->visit(SubExpr))
7734 return false;
7735
7736 if (T == PT_Ptr) {
7737 if (!this->emitIncPtr(E))
7738 return false;
7739
7740 return DiscardResult ? this->emitPopPtr(E) : true;
7741 }
7742
7743 if (T == PT_Float)
7744 return DiscardResult ? this->emitIncfPop(getFPOptions(E), E)
7745 : this->emitIncf(getFPOptions(E), E);
7746
7747 if (SubExpr->refersToBitField())
7748 return DiscardResult ? this->emitIncPopBitfield(*T, E->canOverflow(),
7749 getBitWidth(SubExpr), E)
7750 : this->emitIncBitfield(*T, E->canOverflow(),
7751 getBitWidth(SubExpr), E);
7752
7753 return DiscardResult ? this->emitIncPop(*T, E->canOverflow(), E)
7754 : this->emitInc(*T, E->canOverflow(), E);
7755 }
7756 case UO_PostDec: { // x--
7757 if (!Ctx.getLangOpts().CPlusPlus14)
7758 return this->emitInvalid(E);
7759 if (!T)
7760 return this->emitError(E);
7761
7762 if (!this->visit(SubExpr))
7763 return false;
7764
7765 if (T == PT_Ptr) {
7766 if (!this->emitDecPtr(E))
7767 return false;
7768
7769 return DiscardResult ? this->emitPopPtr(E) : true;
7770 }
7771
7772 if (T == PT_Float)
7773 return DiscardResult ? this->emitDecfPop(getFPOptions(E), E)
7774 : this->emitDecf(getFPOptions(E), E);
7775
7776 if (SubExpr->refersToBitField()) {
7777 return DiscardResult ? this->emitDecPopBitfield(*T, E->canOverflow(),
7778 getBitWidth(SubExpr), E)
7779 : this->emitDecBitfield(*T, E->canOverflow(),
7780 getBitWidth(SubExpr), E);
7781 }
7782
7783 return DiscardResult ? this->emitDecPop(*T, E->canOverflow(), E)
7784 : this->emitDec(*T, E->canOverflow(), E);
7785 }
7786 case UO_PreInc: { // ++x
7787 if (!Ctx.getLangOpts().CPlusPlus14)
7788 return this->emitInvalid(E);
7789 if (!T)
7790 return this->emitError(E);
7791
7792 if (!this->visit(SubExpr))
7793 return false;
7794
7795 if (T == PT_Ptr) {
7796 if (!this->emitLoadPtr(E))
7797 return false;
7798 if (!this->emitConstUint8(1, E))
7799 return false;
7800 if (!this->emitAddOffsetUint8(E))
7801 return false;
7802 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
7803 }
7804
7805 // Post-inc and pre-inc are the same if the value is to be discarded.
7806 if (DiscardResult) {
7807 if (T == PT_Float)
7808 return this->emitIncfPop(getFPOptions(E), E);
7809 if (SubExpr->refersToBitField())
7810 return DiscardResult ? this->emitIncPopBitfield(*T, E->canOverflow(),
7811 getBitWidth(SubExpr), E)
7812 : this->emitIncBitfield(*T, E->canOverflow(),
7813 getBitWidth(SubExpr), E);
7814 return this->emitIncPop(*T, E->canOverflow(), E);
7815 }
7816
7817 if (T == PT_Float) {
7818 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
7819 if (!this->emitLoadFloat(E))
7820 return false;
7821 APFloat F(TargetSemantics, 1);
7822 if (!this->emitFloat(F, E))
7823 return false;
7824
7825 if (!this->emitAddf(getFPOptions(E), E))
7826 return false;
7827 if (!this->emitStoreFloat(E))
7828 return false;
7829 } else if (SubExpr->refersToBitField()) {
7830 assert(isIntegerOrBoolType(*T));
7831 if (!this->emitPreIncBitfield(*T, E->canOverflow(), getBitWidth(SubExpr),
7832 E))
7833 return false;
7834 } else {
7835 assert(isIntegerOrBoolType(*T));
7836 if (!this->emitPreInc(*T, E->canOverflow(), E))
7837 return false;
7838 }
7839 return E->isGLValue() || this->emitLoadPop(*T, E);
7840 }
7841 case UO_PreDec: { // --x
7842 if (!Ctx.getLangOpts().CPlusPlus14)
7843 return this->emitInvalid(E);
7844 if (!T)
7845 return this->emitError(E);
7846
7847 if (!this->visit(SubExpr))
7848 return false;
7849
7850 if (T == PT_Ptr) {
7851 if (!this->emitLoadPtr(E))
7852 return false;
7853 if (!this->emitConstUint8(1, E))
7854 return false;
7855 if (!this->emitSubOffsetUint8(E))
7856 return false;
7857 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
7858 }
7859
7860 // Post-dec and pre-dec are the same if the value is to be discarded.
7861 if (DiscardResult) {
7862 if (T == PT_Float)
7863 return this->emitDecfPop(getFPOptions(E), E);
7864 if (SubExpr->refersToBitField())
7865 return DiscardResult ? this->emitDecPopBitfield(*T, E->canOverflow(),
7866 getBitWidth(SubExpr), E)
7867 : this->emitDecBitfield(*T, E->canOverflow(),
7868 getBitWidth(SubExpr), E);
7869 return this->emitDecPop(*T, E->canOverflow(), E);
7870 }
7871
7872 if (T == PT_Float) {
7873 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
7874 if (!this->emitLoadFloat(E))
7875 return false;
7876 APFloat F(TargetSemantics, 1);
7877 if (!this->emitFloat(F, E))
7878 return false;
7879
7880 if (!this->emitSubf(getFPOptions(E), E))
7881 return false;
7882 if (!this->emitStoreFloat(E))
7883 return false;
7884 } else if (SubExpr->refersToBitField()) {
7885 assert(isIntegerOrBoolType(*T));
7886 if (!this->emitPreDecBitfield(*T, E->canOverflow(), getBitWidth(SubExpr),
7887 E))
7888 return false;
7889 } else {
7890 assert(isIntegerOrBoolType(*T));
7891 if (!this->emitPreDec(*T, E->canOverflow(), E))
7892 return false;
7893 }
7894 return E->isGLValue() || this->emitLoadPop(*T, E);
7895 }
7896 case UO_LNot: // !x
7897 if (!T)
7898 return this->emitError(E);
7899
7900 if (DiscardResult)
7901 return this->discard(SubExpr);
7902
7903 if (!this->visitBool(SubExpr))
7904 return false;
7905
7906 if (!this->emitInv(E))
7907 return false;
7908
7909 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
7910 return this->emitCast(PT_Bool, ET, E);
7911 return true;
7912 case UO_Minus: // -x
7913 if (!T)
7914 return this->emitError(E);
7915
7916 if (!this->visit(SubExpr))
7917 return false;
7918 return DiscardResult ? this->emitPop(*T, E) : this->emitNeg(*T, E);
7919 case UO_Plus: // +x
7920 if (!T)
7921 return this->emitError(E);
7922
7923 if (!this->visit(SubExpr)) // noop
7924 return false;
7925 return DiscardResult ? this->emitPop(*T, E) : true;
7926 case UO_AddrOf: // &x
7927 if (E->getType()->isMemberPointerType()) {
7928 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7929 // member can be formed.
7930 if (DiscardResult)
7931 return true;
7932 return this->emitGetMemberPtr(cast<DeclRefExpr>(SubExpr)->getDecl(), E);
7933 }
7934 // [C11 6.5.3.2p3]: if the operand of '&' is the result of a unary '*'
7935 // operator, neither operator is evaluated and the result is as if both
7936 // were omitted. So '&*q' is just 'q' with no dereference; delegate to the
7937 // pointer operand directly instead of to the '*' (which would emit a null
7938 // check), so that e.g. '&*(int *)0' is not rejected.
7939 if (!Ctx.getLangOpts().CPlusPlus) {
7940 const Expr *Sub = SubExpr->IgnoreParens();
7941 if (const auto *Deref = dyn_cast<UnaryOperator>(Sub);
7942 Deref && Deref->getOpcode() == UO_Deref)
7943 return this->delegate(Deref->getSubExpr());
7944 }
7945 // We should already have a pointer when we get here.
7946 return this->delegate(SubExpr);
7947 case UO_Deref: // *x
7948 if (DiscardResult)
7949 return this->discard(SubExpr);
7950
7951 if (!this->visit(SubExpr))
7952 return false;
7953
7954 if (!SubExpr->getType()->isFunctionPointerType() && !this->emitCheckNull(E))
7955 return false;
7956
7957 if (classifyPrim(SubExpr) == PT_Ptr)
7958 return this->emitNarrowPtr(E);
7959 return true;
7960
7961 case UO_Not: // ~x
7962 if (!T)
7963 return this->emitError(E);
7964
7965 if (!this->visit(SubExpr))
7966 return false;
7967 return DiscardResult ? this->emitPop(*T, E) : this->emitComp(*T, E);
7968 case UO_Real: // __real x
7969 if (!T)
7970 return false;
7971 return this->delegate(SubExpr);
7972 case UO_Imag: { // __imag x
7973 if (!T)
7974 return false;
7975 if (!this->discard(SubExpr))
7976 return false;
7977 return DiscardResult
7978 ? true
7979 : this->visitZeroInitializer(*T, SubExpr->getType(), SubExpr);
7980 }
7981 case UO_Extension:
7982 return this->delegate(SubExpr);
7983 case UO_Coawait:
7984 assert(false && "Unhandled opcode");
7985 }
7986
7987 return false;
7988}
7989
7990template <class Emitter>
7992 const Expr *SubExpr = E->getSubExpr();
7993 assert(SubExpr->getType()->isAnyComplexType());
7994
7995 if (DiscardResult)
7996 return this->discard(SubExpr);
7997
7998 OptPrimType ResT = classify(E);
7999 auto prepareResult = [=]() -> bool {
8000 if (!ResT && !Initializing) {
8001 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
8002 if (!LocalIndex)
8003 return false;
8004 return this->emitGetPtrLocal(*LocalIndex, E);
8005 }
8006
8007 return true;
8008 };
8009
8010 // The offset of the temporary, if we created one.
8011 unsigned SubExprOffset = ~0u;
8012 auto createTemp = [=, &SubExprOffset]() -> bool {
8013 SubExprOffset =
8014 this->allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
8015 if (!this->visit(SubExpr))
8016 return false;
8017 return this->emitSetLocal(PT_Ptr, SubExprOffset, E);
8018 };
8019
8020 PrimType ElemT = classifyComplexElementType(SubExpr->getType());
8021 auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
8022 if (!this->emitGetLocal(PT_Ptr, Offset, E))
8023 return false;
8024 return this->emitArrayElemPop(ElemT, Index, E);
8025 };
8026
8027 switch (E->getOpcode()) {
8028 case UO_Minus: // -x
8029 if (!prepareResult())
8030 return false;
8031 if (!createTemp())
8032 return false;
8033 for (unsigned I = 0; I != 2; ++I) {
8034 if (!getElem(SubExprOffset, I))
8035 return false;
8036 if (!this->emitNeg(ElemT, E))
8037 return false;
8038 if (!this->emitInitElem(ElemT, I, E))
8039 return false;
8040 }
8041 break;
8042
8043 case UO_Plus: // +x
8044 case UO_AddrOf: // &x
8045 case UO_Deref: // *x
8046 return this->delegate(SubExpr);
8047
8048 case UO_LNot:
8049 if (!this->visit(SubExpr))
8050 return false;
8051 if (!this->emitComplexBoolCast(SubExpr))
8052 return false;
8053 if (!this->emitInv(E))
8054 return false;
8055 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
8056 return this->emitCast(PT_Bool, ET, E);
8057 return true;
8058
8059 case UO_Real:
8060 return this->emitComplexReal(SubExpr);
8061
8062 case UO_Imag:
8063 if (!this->visit(SubExpr))
8064 return false;
8065
8066 if (SubExpr->isLValue()) {
8067 if (!this->emitConstUint8(1, E))
8068 return false;
8069 return this->emitArrayElemPtrPopUint8(E);
8070 }
8071
8072 // Since our _Complex implementation does not map to a primitive type,
8073 // we sometimes have to do the lvalue-to-rvalue conversion here manually.
8074 return this->emitArrayElemPop(classifyPrim(E->getType()), 1, E);
8075
8076 case UO_Not: // ~x
8077 if (!this->delegate(SubExpr))
8078 return false;
8079 // Negate the imaginary component.
8080 if (!this->emitArrayElem(ElemT, 1, E))
8081 return false;
8082 if (!this->emitNeg(ElemT, E))
8083 return false;
8084 if (!this->emitInitElem(ElemT, 1, E))
8085 return false;
8086 return DiscardResult ? this->emitPopPtr(E) : true;
8087
8088 case UO_Extension:
8089 return this->delegate(SubExpr);
8090
8091 default:
8092 return this->emitInvalid(E);
8093 }
8094
8095 return true;
8096}
8097
8098template <class Emitter>
8100 const Expr *SubExpr = E->getSubExpr();
8101 assert(SubExpr->getType()->isVectorType());
8102
8103 if (DiscardResult)
8104 return this->discard(SubExpr);
8105
8106 auto UnaryOp = E->getOpcode();
8107 if (UnaryOp == UO_Extension)
8108 return this->delegate(SubExpr);
8109
8110 if (UnaryOp != UO_Plus && UnaryOp != UO_Minus && UnaryOp != UO_LNot &&
8111 UnaryOp != UO_Not && UnaryOp != UO_AddrOf)
8112 return this->emitInvalid(E);
8113
8114 // Nothing to do here.
8115 if (UnaryOp == UO_Plus || UnaryOp == UO_AddrOf)
8116 return this->delegate(SubExpr);
8117
8118 if (!Initializing) {
8119 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
8120 if (!LocalIndex)
8121 return false;
8122 if (!this->emitGetPtrLocal(*LocalIndex, E))
8123 return false;
8124 }
8125
8126 // The offset of the temporary, if we created one.
8127 unsigned SubExprOffset =
8128 this->allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
8129 if (!this->visit(SubExpr))
8130 return false;
8131 if (!this->emitSetLocal(PT_Ptr, SubExprOffset, E))
8132 return false;
8133
8134 const auto *VecTy = SubExpr->getType()->getAs<VectorType>();
8135 PrimType ElemT = classifyVectorElementType(SubExpr->getType());
8136 auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
8137 if (!this->emitGetLocal(PT_Ptr, Offset, E))
8138 return false;
8139 return this->emitArrayElemPop(ElemT, Index, E);
8140 };
8141
8142 switch (UnaryOp) {
8143 case UO_Minus:
8144 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8145 if (!getElem(SubExprOffset, I))
8146 return false;
8147 if (!this->emitNeg(ElemT, E))
8148 return false;
8149 if (!this->emitInitElem(ElemT, I, E))
8150 return false;
8151 }
8152 break;
8153 case UO_LNot: { // !x
8154 // In C++, the logic operators !, &&, || are available for vectors. !v is
8155 // equivalent to v == 0.
8156 //
8157 // The result of the comparison is a vector of the same width and number of
8158 // elements as the comparison operands with a signed integral element type.
8159 //
8160 // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html
8161 QualType ResultVecTy = E->getType();
8162 PrimType ResultVecElemT =
8163 classifyPrim(ResultVecTy->getAs<VectorType>()->getElementType());
8164 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8165 if (!getElem(SubExprOffset, I))
8166 return false;
8167 // operator ! on vectors returns -1 for 'truth', so negate it.
8168 if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
8169 return false;
8170 if (!this->emitInv(E))
8171 return false;
8172 if (!this->emitPrimCast(PT_Bool, ElemT, VecTy->getElementType(), E))
8173 return false;
8174 if (!this->emitNeg(ElemT, E))
8175 return false;
8176 if (ElemT != ResultVecElemT &&
8177 !this->emitPrimCast(ElemT, ResultVecElemT, ResultVecTy, E))
8178 return false;
8179 if (!this->emitInitElem(ResultVecElemT, I, E))
8180 return false;
8181 }
8182 break;
8183 }
8184 case UO_Not: // ~x
8185 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8186 if (!getElem(SubExprOffset, I))
8187 return false;
8188 if (ElemT == PT_Bool) {
8189 if (!this->emitInv(E))
8190 return false;
8191 } else {
8192 if (!this->emitComp(ElemT, E))
8193 return false;
8194 }
8195 if (!this->emitInitElem(ElemT, I, E))
8196 return false;
8197 }
8198 break;
8199 default:
8200 llvm_unreachable("Unsupported unary operators should be handled up front");
8201 }
8202 return true;
8203}
8204
8205template <class Emitter>
8207 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
8208 if (DiscardResult)
8209 return true;
8210 return this->emitConst(ECD->getInitVal(), E);
8211 }
8212 if (const auto *FuncDecl = dyn_cast<FunctionDecl>(D)) {
8213 if (DiscardResult)
8214 return true;
8215 const Function *F = getFunction(FuncDecl);
8216 return F && this->emitGetFnPtr(F, E);
8217 }
8218 if (const auto *TPOD = dyn_cast<TemplateParamObjectDecl>(D)) {
8219 TPOD = TPOD->getFirstDecl();
8220 if (DiscardResult)
8221 return true;
8222 if (UnsignedOrNone GlobalIndex = P.getGlobal(TPOD))
8223 return this->emitGetPtrGlobal(*GlobalIndex, E);
8224
8225 if (UnsignedOrNone Index = P.getOrCreateGlobal(TPOD)) {
8226 if (OptPrimType T = classify(TPOD->getType())) {
8227 if (!this->visitAPValue(TPOD->getValue(), *T, E))
8228 return false;
8229 return this->emitInitGlobal(*T, *Index, E);
8230 }
8231
8232 if (!this->emitGetPtrGlobal(*Index, E))
8233 return false;
8234 if (!this->visitAPValueInitializer(TPOD->getValue(), E, TPOD->getType()))
8235 return false;
8236 return this->emitFinishInit(E);
8237 }
8238 return false;
8239 }
8240
8241 // References are implemented via pointers, so when we see a DeclRefExpr
8242 // pointing to a reference, we need to get its value directly (i.e. the
8243 // pointer to the actual value) instead of a pointer to the pointer to the
8244 // value.
8245 QualType DeclType = D->getType();
8246 bool IsReference = DeclType->isReferenceType();
8247
8248 auto maybePopPtr = [&]() -> bool {
8249 if (DiscardResult)
8250 return this->emitPopPtr(E);
8251 return true;
8252 };
8253
8254 // Function parameters.
8255 // Note that it's important to check them first since we might have a local
8256 // variable created for a ParmVarDecl as well.
8257 if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
8258 if (DiscardResult)
8259 return true;
8260
8261 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
8262 !DeclType->isIntegralOrEnumerationType()) {
8263 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8264 /*InitializerFailed=*/false, E);
8265 }
8266 if (auto It = this->Params.find(PVD); It != this->Params.end()) {
8267 if (IsReference || !It->second.IsPtr)
8268 return this->emitGetParam(classifyPrim(E), It->second.Index, E);
8269
8270 return this->emitGetPtrParam(It->second.Index, E);
8271 }
8272
8273 if (!Ctx.getLangOpts().CPlusPlus23 && IsReference && !Locals.contains(D))
8274 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8275 /*InitializerFailed=*/false, E);
8276 }
8277
8278 // Local variables.
8279 if (auto It = Locals.find(D); It != Locals.end()) {
8280 const unsigned Offset = It->second.Offset;
8281 if (IsReference) {
8282 assert(classifyPrim(E) == PT_Ptr);
8283 return this->emitGetRefLocal(Offset, E) && maybePopPtr();
8284 }
8285 return this->emitGetPtrLocal(Offset, E) && maybePopPtr();
8286 }
8287 // Global variables.
8288 if (auto GlobalIndex = P.getGlobal(D)) {
8289 if (IsReference) {
8290 if (!Ctx.getLangOpts().CPlusPlus11)
8291 return this->emitGetGlobal(classifyPrim(E), *GlobalIndex, E);
8292 if (!Ctx.getLangOpts().CPlusPlus23)
8293 return this->emitGetGlobalUnchecked(classifyPrim(E), *GlobalIndex, E);
8294
8295 return this->emitGetRefGlobal(*GlobalIndex, E) && maybePopPtr();
8296 }
8297
8298 return this->emitGetPtrGlobal(*GlobalIndex, E) && maybePopPtr();
8299 }
8300
8301 // In case we need to re-visit a declaration.
8302 auto revisit = [&](const VarDecl *VD,
8303 bool IsConstexprUnknown = true) -> bool {
8305 IsConstexprUnknown);
8306 if constexpr (std::is_same_v<Emitter, EvalEmitter>) {
8307 if (!this->emitPushCC(VD->hasConstantInitialization(), E))
8308 return false;
8309 }
8310 auto VarState = this->visitDecl(VD);
8311
8312 if constexpr (std::is_same_v<Emitter, EvalEmitter>) {
8313 if (!this->emitPopCC(E))
8314 return false;
8315 }
8316
8317 if (VarState.notCreated())
8318 return true;
8319 if (!VarState)
8320 return false;
8321 // Retry.
8322 return this->visitDeclRef(D, E);
8323 };
8324
8325 if constexpr (!std::is_same_v<Emitter, EvalEmitter>) {
8326 // Lambda captures.
8327 if (auto It = this->LambdaCaptures.find(D);
8328 It != this->LambdaCaptures.end()) {
8329 auto [Offset, IsPtr] = It->second;
8330
8331 if (IsPtr)
8332 return this->emitGetThisFieldPtr(Offset, E) && maybePopPtr();
8333 return this->emitGetPtrThisField(Offset, E) && maybePopPtr();
8334 }
8335 }
8336
8337 if (const auto *DRE = dyn_cast<DeclRefExpr>(E);
8338 DRE && DRE->refersToEnclosingVariableOrCapture()) {
8339 if (const auto *VD = dyn_cast<VarDecl>(D); VD && VD->isInitCapture())
8340 return revisit(VD);
8341 }
8342
8343 if (const auto *BD = dyn_cast<BindingDecl>(D))
8344 return this->delegate(BD->getBinding());
8345
8346 // Avoid infinite recursion.
8347 if (D == InitializingDecl) {
8348 if (DiscardResult)
8349 return true;
8350 return this->emitDummyPtr(D, E);
8351 }
8352
8353 // Try to lazily visit (or emit dummy pointers for) declarations
8354 // we haven't seen yet.
8355 const auto *VD = dyn_cast<VarDecl>(D);
8356 if (!VD)
8357 return this->emitError(E);
8358
8359 // For C.
8360 if (!Ctx.getLangOpts().CPlusPlus) {
8361 if (VD->getInit() && !VD->getInit()->isValueDependent() &&
8362 DeclType.isConstant(Ctx.getASTContext()) && !VD->isWeak() &&
8363 VD->evaluateValue())
8364 return revisit(VD, /*IsConstexprUnknown=*/false);
8365
8366 if (DiscardResult)
8367 return true;
8368 return this->emitDummyPtr(D, E);
8369 }
8370
8371 // ... and C++.
8372 const auto typeShouldBeVisited = [&](QualType T) -> bool {
8373 if (T.isConstant(Ctx.getASTContext()))
8374 return true;
8375 return T->isReferenceType();
8376 };
8377
8378 if ((VD->hasGlobalStorage() || VD->isStaticDataMember()) &&
8379 typeShouldBeVisited(DeclType)) {
8380 if (const Expr *Init = VD->getAnyInitializer();
8381 Init && !Init->isValueDependent()) {
8382 // Whether or not the evaluation is successul doesn't really matter
8383 // here -- we will create a global variable in any case, and that
8384 // will have the state of initializer evaluation attached.
8386 (void)Init->EvaluateAsInitializer(Ctx.getASTContext(), VD, Result, true);
8387 return this->visitDeclRef(D, E);
8388 }
8389 return revisit(VD, !VD->isConstexpr() && DeclType->isReferenceType());
8390 }
8391
8392 // FIXME: The evaluateValue() check here is a little ridiculous, since
8393 // it will ultimately call into Context::evaluateAsInitializer(). In
8394 // other words, we're evaluating the initializer, just to know if we can
8395 // evaluate the initializer.
8396 if (VD->isLocalVarDecl() && typeShouldBeVisited(DeclType) && VD->getInit() &&
8397 !VD->getInit()->isValueDependent()) {
8398 if (VD->evaluateValue()) {
8399 bool IsConstexprUnknown = !DeclType.isConstant(Ctx.getASTContext()) &&
8400 !DeclType->isReferenceType();
8401 // Revisit the variable declaration, but make sure it's associated with a
8402 // different evaluation, so e.g. mutable reads don't work on it.
8403 EvalIDScope _(Ctx);
8404 return revisit(VD, IsConstexprUnknown);
8405 } else if (Ctx.getLangOpts().CPlusPlus23 && IsReference)
8406 return revisit(VD, /*IsConstexprUnknown=*/true);
8407
8408 if (IsReference)
8409 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8410 /*InitializerFailed=*/true, E);
8411 }
8412
8413 if (DiscardResult)
8414 return true;
8415 return this->emitDummyPtr(
8416 D, E, Ctx.getLangOpts().CPlusPlus23 && DeclType->isReferenceType());
8417}
8418
8419template <class Emitter>
8421 const auto *D = E->getDecl();
8422 return this->visitDeclRef(D, E);
8423}
8424
8425template <class Emitter>
8427 const DesignatedInitUpdateExpr *E) {
8428 if (!this->visitInitializer(E->getBase()))
8429 return false;
8430 return this->visitInitializer(E->getUpdater());
8431}
8432
8433template <class Emitter> bool Compiler<Emitter>::emitCleanup() {
8434 for (VariableScope<Emitter> *C = VarScope; C; C = C->getParent()) {
8435 if (!C->destroyLocals())
8436 return false;
8437 }
8438 return true;
8439}
8440
8441template <class Emitter>
8442unsigned Compiler<Emitter>::collectBaseOffset(const QualType BaseType,
8443 const QualType DerivedType) {
8444 const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
8445 if (const auto *R = Ty->getPointeeCXXRecordDecl())
8446 return R;
8447 return Ty->getAsCXXRecordDecl();
8448 };
8449 const CXXRecordDecl *BaseDecl = extractRecordDecl(BaseType);
8450 const CXXRecordDecl *DerivedDecl = extractRecordDecl(DerivedType);
8451
8452 return Ctx.collectBaseOffset(BaseDecl, DerivedDecl);
8453}
8454
8455/// Emit casts from a PrimType to another PrimType.
8456template <class Emitter>
8457bool Compiler<Emitter>::emitPrimCast(PrimType FromT, PrimType ToT,
8458 QualType ToQT, const Expr *E) {
8459
8460 if (FromT == PT_Float) {
8461 // Floating to floating.
8462 if (ToT == PT_Float) {
8463 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
8464 return this->emitCastFP(ToSem, getRoundingMode(E), E);
8465 }
8466
8467 if (ToT == PT_IntAP)
8468 return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(ToQT),
8469 getFPOptions(E), E);
8470 if (ToT == PT_IntAPS)
8471 return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(ToQT),
8472 getFPOptions(E), E);
8473
8474 // Float to integral.
8475 if (isIntegerOrBoolType(ToT) || ToT == PT_Bool)
8476 return this->emitCastFloatingIntegral(ToT, getFPOptions(E), E);
8477 }
8478
8479 if (isIntegerOrBoolType(FromT) || FromT == PT_Bool) {
8480 if (ToT == PT_IntAP)
8481 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
8482 if (ToT == PT_IntAPS)
8483 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
8484
8485 // Integral to integral.
8486 if (isIntegerOrBoolType(ToT) || ToT == PT_Bool)
8487 return FromT != ToT ? this->emitCast(FromT, ToT, E) : true;
8488
8489 if (ToT == PT_Float) {
8490 // Integral to floating.
8491 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
8492 return this->emitCastIntegralFloating(FromT, ToSem, getFPOptions(E), E);
8493 }
8494 }
8495
8496 return false;
8497}
8498
8499template <class Emitter>
8500bool Compiler<Emitter>::emitIntegralCast(PrimType FromT, PrimType ToT,
8501 QualType ToQT, const Expr *E) {
8502 assert(FromT != ToT);
8503
8504 if (ToT == PT_IntAP)
8505 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
8506 if (ToT == PT_IntAPS)
8507 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
8508
8509 return this->emitCast(FromT, ToT, E);
8510}
8511
8512/// Emits __real(SubExpr)
8513template <class Emitter>
8514bool Compiler<Emitter>::emitComplexReal(const Expr *SubExpr) {
8515 assert(SubExpr->getType()->isAnyComplexType());
8516
8517 if (DiscardResult)
8518 return this->discard(SubExpr);
8519
8520 if (!this->visit(SubExpr))
8521 return false;
8522 if (SubExpr->isLValue()) {
8523 if (!this->emitConstUint8(0, SubExpr))
8524 return false;
8525 return this->emitArrayElemPtrPopUint8(SubExpr);
8526 }
8527
8528 // Rvalue, load the actual element.
8529 return this->emitArrayElemPop(classifyComplexElementType(SubExpr->getType()),
8530 0, SubExpr);
8531}
8532
8533template <class Emitter>
8534bool Compiler<Emitter>::emitComplexBoolCast(const Expr *E) {
8535 assert(!DiscardResult);
8536 PrimType ElemT = classifyComplexElementType(E->getType());
8537 // We emit the expression (__real(E) != 0 || __imag(E) != 0)
8538 // for us, that means (bool)E[0] || (bool)E[1]
8539 if (!this->emitArrayElem(ElemT, 0, E))
8540 return false;
8541 if (ElemT == PT_Float) {
8542 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
8543 return false;
8544 } else {
8545 if (!this->emitCast(ElemT, PT_Bool, E))
8546 return false;
8547 }
8548
8549 // We now have the bool value of E[0] on the stack.
8550 LabelTy LabelTrue = this->getLabel();
8551 if (!this->jumpTrue(LabelTrue, E))
8552 return false;
8553
8554 if (!this->emitArrayElemPop(ElemT, 1, E))
8555 return false;
8556 if (ElemT == PT_Float) {
8557 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
8558 return false;
8559 } else {
8560 if (!this->emitCast(ElemT, PT_Bool, E))
8561 return false;
8562 }
8563 // Leave the boolean value of E[1] on the stack.
8564 LabelTy EndLabel = this->getLabel();
8565 this->jump(EndLabel, E);
8566
8567 this->emitLabel(LabelTrue);
8568 if (!this->emitPopPtr(E))
8569 return false;
8570 if (!this->emitConstBool(true, E))
8571 return false;
8572
8573 this->fallthrough(EndLabel);
8574 this->emitLabel(EndLabel);
8575
8576 return true;
8577}
8578
8579template <class Emitter>
8580bool Compiler<Emitter>::emitComplexComparison(const Expr *LHS, const Expr *RHS,
8581 const BinaryOperator *E) {
8582 assert(E->isComparisonOp());
8583 assert(!Initializing);
8584 if (DiscardResult)
8585 return this->discard(LHS) && this->discard(RHS);
8586
8587 PrimType ElemT;
8588 bool LHSIsComplex;
8589 unsigned LHSOffset;
8590 if (LHS->getType()->isAnyComplexType()) {
8591 LHSIsComplex = true;
8592 ElemT = classifyComplexElementType(LHS->getType());
8593 LHSOffset = allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true);
8594 if (!this->visit(LHS))
8595 return false;
8596 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
8597 return false;
8598 } else {
8599 LHSIsComplex = false;
8600 PrimType LHST = classifyPrim(LHS->getType());
8601 LHSOffset = this->allocateLocalPrimitive(LHS, LHST, /*IsConst=*/true);
8602 if (!this->visit(LHS))
8603 return false;
8604 if (!this->emitSetLocal(LHST, LHSOffset, E))
8605 return false;
8606 }
8607
8608 bool RHSIsComplex;
8609 unsigned RHSOffset;
8610 if (RHS->getType()->isAnyComplexType()) {
8611 RHSIsComplex = true;
8612 ElemT = classifyComplexElementType(RHS->getType());
8613 RHSOffset = allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true);
8614 if (!this->visit(RHS))
8615 return false;
8616 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
8617 return false;
8618 } else {
8619 RHSIsComplex = false;
8620 PrimType RHST = classifyPrim(RHS->getType());
8621 RHSOffset = this->allocateLocalPrimitive(RHS, RHST, /*IsConst=*/true);
8622 if (!this->visit(RHS))
8623 return false;
8624 if (!this->emitSetLocal(RHST, RHSOffset, E))
8625 return false;
8626 }
8627
8628 auto getElem = [&](unsigned LocalOffset, unsigned Index,
8629 bool IsComplex) -> bool {
8630 if (IsComplex) {
8631 if (!this->emitGetLocal(PT_Ptr, LocalOffset, E))
8632 return false;
8633 return this->emitArrayElemPop(ElemT, Index, E);
8634 }
8635 return this->emitGetLocal(ElemT, LocalOffset, E);
8636 };
8637
8638 for (unsigned I = 0; I != 2; ++I) {
8639 // Get both values.
8640 if (!getElem(LHSOffset, I, LHSIsComplex))
8641 return false;
8642 if (!getElem(RHSOffset, I, RHSIsComplex))
8643 return false;
8644 // And compare them.
8645 if (!this->emitEQ(ElemT, E))
8646 return false;
8647
8648 if (!this->emitCastBoolUint8(E))
8649 return false;
8650 }
8651
8652 // We now have two bool values on the stack. Compare those.
8653 if (!this->emitAddUint8(E))
8654 return false;
8655 if (!this->emitConstUint8(2, E))
8656 return false;
8657
8658 if (E->getOpcode() == BO_EQ) {
8659 if (!this->emitEQUint8(E))
8660 return false;
8661 } else if (E->getOpcode() == BO_NE) {
8662 if (!this->emitNEUint8(E))
8663 return false;
8664 } else
8665 return false;
8666
8667 // In C, this returns an int.
8668 if (PrimType ResT = classifyPrim(E->getType()); ResT != PT_Bool)
8669 return this->emitCast(PT_Bool, ResT, E);
8670 return true;
8671}
8672
8673/// When calling this, we have a pointer of the local-to-destroy
8674/// on the stack.
8675/// Emit destruction of record types (or arrays of record types).
8676template <class Emitter>
8677bool Compiler<Emitter>::emitRecordDestructionPop(const Record *R,
8678 SourceInfo Loc) {
8679 assert(R);
8680 assert(!R->hasTrivialDtor());
8681 const CXXDestructorDecl *Dtor = R->getDestructor();
8682 assert(Dtor);
8683 const Function *DtorFunc = getFunction(Dtor);
8684 if (!DtorFunc)
8685 return false;
8686 assert(DtorFunc->hasThisPointer());
8687 assert(DtorFunc->getNumParams() == 1);
8688 return this->emitCall(DtorFunc, 0, Loc);
8689}
8690/// When calling this, we have a pointer of the local-to-destroy
8691/// on the stack.
8692/// Emit destruction of record types (or arrays of record types).
8693template <class Emitter>
8694bool Compiler<Emitter>::emitDestructionPop(const Descriptor *Desc,
8695 SourceInfo Loc) {
8696 assert(Desc);
8697 assert(!Desc->hasTrivialDtor());
8698
8699 // Arrays.
8700 if (Desc->isArray()) {
8701 const Descriptor *ElemDesc = Desc->ElemDesc;
8702 assert(ElemDesc);
8703
8704 unsigned N = Desc->getNumElems();
8705 if (N == 0)
8706 return this->emitPopPtr(Loc);
8707
8708 for (ssize_t I = N - 1; I >= 1; --I) {
8709 if (!this->emitConstUint64(I, Loc))
8710 return false;
8711 if (!this->emitArrayElemPtrUint64(Loc))
8712 return false;
8713 if (!this->emitDestructionPop(ElemDesc, Loc))
8714 return false;
8715 }
8716 // Last iteration, removes the instance pointer from the stack.
8717 if (!this->emitConstUint64(0, Loc))
8718 return false;
8719 if (!this->emitArrayElemPtrPopUint64(Loc))
8720 return false;
8721 return this->emitDestructionPop(ElemDesc, Loc);
8722 }
8723
8724 assert(Desc->ElemRecord);
8725 assert(!Desc->ElemRecord->hasTrivialDtor());
8726 return this->emitRecordDestructionPop(Desc->ElemRecord, Loc);
8727}
8728
8729/// Create a dummy pointer for the given decl (or expr) and
8730/// push a pointer to it on the stack.
8731template <class Emitter>
8732bool Compiler<Emitter>::emitDummyPtr(DeclOrExpr D, const Expr *E, bool CU) {
8733 assert(!DiscardResult && "Should've been checked before");
8734
8735 if (ToLValue) {
8736 if (const auto *VD = D.asValueDecl())
8737 return this->emitGetOpaquePtr(VD, CU, E);
8738 }
8739
8740 unsigned DummyID = P.getOrCreateDummy(D, CU);
8741 if (!this->emitGetPtrGlobal(DummyID, E))
8742 return false;
8743 if (E->getType()->isVoidType())
8744 return true;
8745
8746 // Convert the dummy pointer to another pointer type if we have to.
8747 if (PrimType PT = classifyPrim(E); PT != PT_Ptr) {
8748 if (isPtrType(PT))
8749 return this->emitDecayPtr(PT_Ptr, PT, E);
8750 return false;
8751 }
8752 return true;
8753}
8754
8755template <class Emitter>
8756bool Compiler<Emitter>::emitFloat(const APFloat &F, SourceInfo Info) {
8757 if (Floating::singleWord(F.getSemantics()))
8758 return this->emitConstFloat(Floating(F), Info);
8759
8760 APInt I = F.bitcastToAPInt();
8761 return this->emitConstFloat(
8762 Floating(const_cast<uint64_t *>(I.getRawData()),
8763 llvm::APFloatBase::SemanticsToEnum(F.getSemantics())),
8764 Info);
8765}
8766
8767// This function is constexpr if and only if To, From, and the types of
8768// all subobjects of To and From are types T such that...
8769// (3.1) - is_union_v<T> is false;
8770// (3.2) - is_pointer_v<T> is false;
8771// (3.3) - is_member_pointer_v<T> is false;
8772// (3.4) - is_volatile_v<T> is false; and
8773// (3.5) - T has no non-static data members of reference type
8774template <class Emitter>
8775bool Compiler<Emitter>::emitBuiltinBitCast(const CastExpr *E) {
8776 const Expr *SubExpr = E->getSubExpr();
8777 QualType FromType = SubExpr->getType();
8778 QualType ToType = E->getType();
8779 OptPrimType ToT = classify(ToType);
8780
8781 assert(!ToType->isReferenceType());
8782
8783 // Prepare storage for the result in case we discard.
8784 if (DiscardResult && !Initializing && !ToT) {
8785 UnsignedOrNone LocalIndex = allocateLocal(E);
8786 if (!LocalIndex)
8787 return false;
8788 if (!this->emitGetPtrLocal(*LocalIndex, E))
8789 return false;
8790 }
8791
8792 // Get a pointer to the value-to-cast on the stack.
8793 // For CK_LValueToRValueBitCast, this is always an lvalue and
8794 // we later assume it to be one (i.e. a PT_Ptr). However,
8795 // we call this function for other utility methods where
8796 // a bitcast might be useful, so convert it to a PT_Ptr in that case.
8797 if (SubExpr->isGLValue() || FromType->isVectorType()) {
8798 if (!this->visit(SubExpr))
8799 return false;
8800 } else if (OptPrimType FromT = classify(SubExpr)) {
8801 unsigned TempOffset =
8802 allocateLocalPrimitive(SubExpr, *FromT, /*IsConst=*/true);
8803 if (!this->visit(SubExpr))
8804 return false;
8805 if (!this->emitSetLocal(*FromT, TempOffset, E))
8806 return false;
8807 if (!this->emitGetPtrLocal(TempOffset, E))
8808 return false;
8809 } else {
8810 return false;
8811 }
8812
8813 if (!ToT) {
8814 if (!this->emitBitCast(E))
8815 return false;
8816 return DiscardResult ? this->emitPopPtr(E) : true;
8817 }
8818 assert(ToT);
8819
8820 const llvm::fltSemantics *TargetSemantics = nullptr;
8821 if (ToT == PT_Float)
8822 TargetSemantics = &Ctx.getFloatSemantics(ToType);
8823
8824 // Conversion to a primitive type. FromType can be another
8825 // primitive type, or a record/array.
8826 bool ToTypeIsUChar = (ToType->isSpecificBuiltinType(BuiltinType::UChar) ||
8827 ToType->isSpecificBuiltinType(BuiltinType::Char_U));
8828 uint32_t ResultBitWidth = std::max(Ctx.getBitWidth(ToType), 8u);
8829
8830 if (!this->emitBitCastPrim(*ToT, ToTypeIsUChar || ToType->isStdByteType(),
8831 ResultBitWidth, TargetSemantics,
8832 ToType.getTypePtr(), E))
8833 return false;
8834
8835 if (DiscardResult)
8836 return this->emitPop(*ToT, E);
8837
8838 return true;
8839}
8840
8841/// Replicate a scalar value into every scalar element of an aggregate.
8842/// The scalar is stored in a local at \p SrcOffset and a pointer to the
8843/// destination must be on top of the interpreter stack. Each element receives
8844/// the scalar, cast to its own type.
8845template <class Emitter>
8846bool Compiler<Emitter>::emitHLSLAggregateSplat(PrimType SrcT,
8847 unsigned SrcOffset,
8848 QualType DestType,
8849 const Expr *E) {
8850 // Vectors and matrices are treated as flat sequences of elements.
8851 unsigned NumElems = 0;
8852 QualType ElemType;
8853 if (const auto *VT = DestType->getAs<VectorType>()) {
8854 NumElems = VT->getNumElements();
8855 ElemType = VT->getElementType();
8856 } else if (const auto *MT = DestType->getAs<ConstantMatrixType>()) {
8857 NumElems = MT->getNumElementsFlattened();
8858 ElemType = MT->getElementType();
8859 }
8860 if (NumElems > 0) {
8861 PrimType ElemT = classifyPrim(ElemType);
8862 for (unsigned I = 0; I != NumElems; ++I) {
8863 if (!this->emitGetLocal(SrcT, SrcOffset, E))
8864 return false;
8865 if (!this->emitPrimCast(SrcT, ElemT, ElemType, E))
8866 return false;
8867 if (!this->emitInitElem(ElemT, I, E))
8868 return false;
8869 }
8870 return true;
8871 }
8872
8873 // Arrays: primitive elements are filled directly; composite elements
8874 // require recursion into each sub-aggregate.
8875 if (const auto *AT = DestType->getAsArrayTypeUnsafe()) {
8876 const auto *CAT = cast<ConstantArrayType>(AT);
8877 QualType ArrElemType = CAT->getElementType();
8878 unsigned ArrSize = CAT->getZExtSize();
8879
8880 if (OptPrimType ElemT = classify(ArrElemType)) {
8881 for (unsigned I = 0; I != ArrSize; ++I) {
8882 if (!this->emitGetLocal(SrcT, SrcOffset, E))
8883 return false;
8884 if (!this->emitPrimCast(SrcT, *ElemT, ArrElemType, E))
8885 return false;
8886 if (!this->emitInitElem(*ElemT, I, E))
8887 return false;
8888 }
8889 } else {
8890 for (unsigned I = 0; I != ArrSize; ++I) {
8891 if (!this->emitConstUint32(I, E))
8892 return false;
8893 if (!this->emitArrayElemPtrUint32(E))
8894 return false;
8895 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, ArrElemType, E))
8896 return false;
8897 if (!this->emitFinishInitPop(E))
8898 return false;
8899 }
8900 }
8901 return true;
8902 }
8903
8904 // Records: fill base classes first, then named fields in declaration
8905 // order.
8906 if (DestType->isRecordType()) {
8907 const Record *R = getRecord(DestType);
8908 if (!R)
8909 return false;
8910
8911 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
8912 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
8913 const Record::Base *B = R->getBase(BS.getType());
8914 assert(B);
8915 if (!this->emitGetPtrBase(B->Offset, E))
8916 return false;
8917 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, BS.getType(), E))
8918 return false;
8919 if (!this->emitFinishInitPop(E))
8920 return false;
8921 }
8922 }
8923
8924 for (const Record::Field &F : R->fields()) {
8925 if (F.isUnnamedBitField())
8926 continue;
8927
8928 QualType FieldType = F.Decl->getType();
8929 if (OptPrimType FieldT = classify(FieldType)) {
8930 if (!this->emitGetLocal(SrcT, SrcOffset, E))
8931 return false;
8932 if (!this->emitPrimCast(SrcT, *FieldT, FieldType, E))
8933 return false;
8934 if (F.isBitField()) {
8935 if (!this->emitInitBitField(*FieldT, F.Offset, F.bitWidth(), E))
8936 return false;
8937 } else {
8938 if (!this->emitInitField(*FieldT, F.Offset, E))
8939 return false;
8940 }
8941 } else {
8942 if (!this->emitGetPtrField(F.Offset, E))
8943 return false;
8944 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, FieldType, E))
8945 return false;
8946 if (!this->emitPopPtr(E))
8947 return false;
8948 }
8949 }
8950 return true;
8951 }
8952
8953 return false;
8954}
8955
8956/// Return the total number of scalar elements in a type. This is used
8957/// to cap how many source elements are extracted during an elementwise cast,
8958/// so we never flatten more than the destination can hold.
8959template <class Emitter>
8960unsigned Compiler<Emitter>::countHLSLFlatElements(QualType Ty) {
8961 // Vector and matrix types are treated as flat sequences of elements.
8962 if (const auto *VT = Ty->getAs<VectorType>())
8963 return VT->getNumElements();
8964 if (const auto *MT = Ty->getAs<ConstantMatrixType>())
8965 return MT->getNumElementsFlattened();
8966 // Arrays: total count is array size * scalar elements per element.
8967 if (const auto *AT = Ty->getAsArrayTypeUnsafe()) {
8968 const auto *CAT = cast<ConstantArrayType>(AT);
8969 return CAT->getZExtSize() * countHLSLFlatElements(CAT->getElementType());
8970 }
8971 // Records: sum scalar element counts of base classes and named fields.
8972 if (Ty->isRecordType()) {
8973 const Record *R = getRecord(Ty);
8974 if (!R)
8975 return 0;
8976 unsigned Count = 0;
8977 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
8978 for (const CXXBaseSpecifier &BS : CXXRD->bases())
8979 Count += countHLSLFlatElements(BS.getType());
8980 }
8981 for (const Record::Field &F : R->fields()) {
8982 if (F.isUnnamedBitField())
8983 continue;
8984 Count += countHLSLFlatElements(F.Decl->getType());
8985 }
8986 return Count;
8987 }
8988 // Scalar primitive types contribute one element.
8989 if (canClassify(Ty))
8990 return 1;
8991 return 0;
8992}
8993
8994/// Walk a source aggregate and extract every scalar element into its own local
8995/// variable. The results are appended to \p Elements in declaration order,
8996/// stopping once \p MaxElements have been collected. A pointer to the
8997/// source aggregate must be stored in the local at \p SrcOffset.
8998template <class Emitter>
8999bool Compiler<Emitter>::emitHLSLFlattenAggregate(
9000 QualType SrcType, unsigned SrcOffset,
9001 SmallVectorImpl<HLSLFlatElement> &Elements, unsigned MaxElements,
9002 const Expr *E) {
9003
9004 // Save a scalar value from the stack into a new local and record it.
9005 auto saveToLocal = [&](PrimType T) -> bool {
9006 unsigned Offset = allocateLocalPrimitive(E, T, /*IsConst=*/true);
9007 if (!this->emitSetLocal(T, Offset, E))
9008 return false;
9009 Elements.push_back({Offset, T});
9010 return true;
9011 };
9012
9013 // Save a pointer from the stack into a new local for later use.
9014 auto savePtrToLocal = [&]() -> UnsignedOrNone {
9015 unsigned Offset = allocateLocalPrimitive(E, PT_Ptr, /*IsConst=*/true);
9016 if (!this->emitSetLocal(PT_Ptr, Offset, E))
9017 return std::nullopt;
9018 return Offset;
9019 };
9020
9021 // Vectors and matrices are flat sequences of elements.
9022 unsigned NumElems = 0;
9023 QualType ElemType;
9024 if (const auto *VT = SrcType->getAs<VectorType>()) {
9025 NumElems = VT->getNumElements();
9026 ElemType = VT->getElementType();
9027 } else if (const auto *MT = SrcType->getAs<ConstantMatrixType>()) {
9028 NumElems = MT->getNumElementsFlattened();
9029 ElemType = MT->getElementType();
9030 }
9031 if (NumElems > 0) {
9032 PrimType ElemT = classifyPrim(ElemType);
9033 for (unsigned I = 0; I != NumElems && Elements.size() < MaxElements; ++I) {
9034 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9035 return false;
9036 if (!this->emitArrayElemPop(ElemT, I, E))
9037 return false;
9038 if (!saveToLocal(ElemT))
9039 return false;
9040 }
9041 return true;
9042 }
9043
9044 // Arrays: primitive elements are extracted directly; composite elements
9045 // require recursion into each sub-aggregate.
9046 if (const auto *AT = SrcType->getAsArrayTypeUnsafe()) {
9047 const auto *CAT = cast<ConstantArrayType>(AT);
9048 QualType ArrElemType = CAT->getElementType();
9049 unsigned ArrSize = CAT->getZExtSize();
9050
9051 if (OptPrimType ElemT = classify(ArrElemType)) {
9052 for (unsigned I = 0; I != ArrSize && Elements.size() < MaxElements; ++I) {
9053 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9054 return false;
9055 if (!this->emitArrayElemPop(*ElemT, I, E))
9056 return false;
9057 if (!saveToLocal(*ElemT))
9058 return false;
9059 }
9060 } else {
9061 for (unsigned I = 0; I != ArrSize && Elements.size() < MaxElements; ++I) {
9062 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9063 return false;
9064 if (!this->emitConstUint32(I, E))
9065 return false;
9066 if (!this->emitArrayElemPtrPopUint32(E))
9067 return false;
9068 UnsignedOrNone ElemPtrOffset = savePtrToLocal();
9069 if (!ElemPtrOffset)
9070 return false;
9071 if (!emitHLSLFlattenAggregate(ArrElemType, *ElemPtrOffset, Elements,
9072 MaxElements, E))
9073 return false;
9074 }
9075 }
9076 return true;
9077 }
9078
9079 // Records: base classes come first, then named fields in declaration
9080 // order.
9081 if (SrcType->isRecordType()) {
9082 const Record *R = getRecord(SrcType);
9083 if (!R)
9084 return false;
9085
9086 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
9087 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
9088 if (Elements.size() >= MaxElements)
9089 break;
9090 const Record::Base *B = R->getBase(BS.getType());
9091 assert(B);
9092 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9093 return false;
9094 if (!this->emitGetPtrBasePop(B->Offset, /*NullOK=*/false, E))
9095 return false;
9096 UnsignedOrNone BasePtrOffset = savePtrToLocal();
9097 if (!BasePtrOffset)
9098 return false;
9099 if (!emitHLSLFlattenAggregate(BS.getType(), *BasePtrOffset, Elements,
9100 MaxElements, E))
9101 return false;
9102 }
9103 }
9104
9105 for (const Record::Field &F : R->fields()) {
9106 if (Elements.size() >= MaxElements)
9107 break;
9108 if (F.isUnnamedBitField())
9109 continue;
9110
9111 QualType FieldType = F.Decl->getType();
9112 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9113 return false;
9114 if (!this->emitGetPtrFieldPop(F.Offset, E))
9115 return false;
9116
9117 if (OptPrimType FieldT = classify(FieldType)) {
9118 if (!this->emitLoadPop(*FieldT, E))
9119 return false;
9120 if (!saveToLocal(*FieldT))
9121 return false;
9122 } else {
9123 UnsignedOrNone FieldPtrOffset = savePtrToLocal();
9124 if (!FieldPtrOffset)
9125 return false;
9126 if (!emitHLSLFlattenAggregate(FieldType, *FieldPtrOffset, Elements,
9127 MaxElements, E))
9128 return false;
9129 }
9130 }
9131 return true;
9132 }
9133
9134 return false;
9135}
9136
9137/// Populate an HLSL aggregate from a flat list of previously extracted source
9138/// elements, casting each to the corresponding destination element type.
9139/// \p ElemIdx tracks the current position in \p Elements and is advanced as
9140/// elements are consumed. A pointer to the destination must be on top of the
9141/// interpreter stack.
9142template <class Emitter>
9143bool Compiler<Emitter>::emitHLSLConstructAggregate(
9144 QualType DestType, ArrayRef<HLSLFlatElement> Elements, unsigned &ElemIdx,
9145 const Expr *E) {
9146
9147 // Consume the next source element, cast it, and leave it on the stack.
9148 auto loadAndCast = [&](PrimType DestT, QualType DestQT) -> bool {
9149 const auto &Src = Elements[ElemIdx++];
9150 if (!this->emitGetLocal(Src.Type, Src.LocalOffset, E))
9151 return false;
9152 return this->emitPrimCast(Src.Type, DestT, DestQT, E);
9153 };
9154
9155 // Vectors and matrices are flat sequences of elements.
9156 unsigned NumElems = 0;
9157 QualType ElemType;
9158 if (const auto *VT = DestType->getAs<VectorType>()) {
9159 NumElems = VT->getNumElements();
9160 ElemType = VT->getElementType();
9161 } else if (const auto *MT = DestType->getAs<ConstantMatrixType>()) {
9162 NumElems = MT->getNumElementsFlattened();
9163 ElemType = MT->getElementType();
9164 }
9165 if (NumElems > 0) {
9166 PrimType DestElemT = classifyPrim(ElemType);
9167 for (unsigned I = 0; I != NumElems; ++I) {
9168 if (!loadAndCast(DestElemT, ElemType))
9169 return false;
9170 if (!this->emitInitElem(DestElemT, I, E))
9171 return false;
9172 }
9173 return true;
9174 }
9175
9176 // Arrays: primitive elements are filled directly; composite elements
9177 // require recursion into each sub-aggregate.
9178 if (const auto *AT = DestType->getAsArrayTypeUnsafe()) {
9179 const auto *CAT = cast<ConstantArrayType>(AT);
9180 QualType ArrElemType = CAT->getElementType();
9181 unsigned ArrSize = CAT->getZExtSize();
9182
9183 if (OptPrimType ElemT = classify(ArrElemType)) {
9184 for (unsigned I = 0; I != ArrSize; ++I) {
9185 if (!loadAndCast(*ElemT, ArrElemType))
9186 return false;
9187 if (!this->emitInitElem(*ElemT, I, E))
9188 return false;
9189 }
9190 } else {
9191 for (unsigned I = 0; I != ArrSize; ++I) {
9192 if (!this->emitConstUint32(I, E))
9193 return false;
9194 if (!this->emitArrayElemPtrUint32(E))
9195 return false;
9196 if (!emitHLSLConstructAggregate(ArrElemType, Elements, ElemIdx, E))
9197 return false;
9198 if (!this->emitFinishInitPop(E))
9199 return false;
9200 }
9201 }
9202 return true;
9203 }
9204
9205 // Records: base classes come first, then named fields in declaration
9206 // order.
9207 if (DestType->isRecordType()) {
9208 const Record *R = getRecord(DestType);
9209 if (!R)
9210 return false;
9211
9212 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
9213 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
9214 const Record::Base *B = R->getBase(BS.getType());
9215 assert(B);
9216 if (!this->emitGetPtrBase(B->Offset, E))
9217 return false;
9218 if (!emitHLSLConstructAggregate(BS.getType(), Elements, ElemIdx, E))
9219 return false;
9220 if (!this->emitFinishInitPop(E))
9221 return false;
9222 }
9223 }
9224
9225 for (const Record::Field &F : R->fields()) {
9226 if (F.isUnnamedBitField())
9227 continue;
9228
9229 QualType FieldType = F.Decl->getType();
9230 if (OptPrimType FieldT = classify(FieldType)) {
9231 if (!loadAndCast(*FieldT, FieldType))
9232 return false;
9233 if (F.isBitField()) {
9234 if (!this->emitInitBitField(*FieldT, F.Offset, F.bitWidth(), E))
9235 return false;
9236 } else {
9237 if (!this->emitInitField(*FieldT, F.Offset, E))
9238 return false;
9239 }
9240 } else {
9241 if (!this->emitGetPtrField(F.Offset, E))
9242 return false;
9243 if (!emitHLSLConstructAggregate(FieldType, Elements, ElemIdx, E))
9244 return false;
9245 if (!this->emitPopPtr(E))
9246 return false;
9247 }
9248 }
9249 return true;
9250 }
9251
9252 return false;
9253}
9254
9255namespace clang {
9256namespace interp {
9257
9258template class Compiler<ByteCodeEmitter>;
9259template class Compiler<EvalEmitter>;
9260
9261} // namespace interp
9262} // namespace clang
#define V(N, I)
static void emit(Program &P, llvm::SmallVectorImpl< std::byte > &Code, const T &Val, bool &Success)
Helper to write bytecode and bail out if 32-bit offsets become invalid.
static void emitCleanup(CIRGenFunction &cgf, cir::CleanupScopeOp cleanupScope, EHScopeStack::Cleanup *cleanup, EHScopeStack::Cleanup::Flags flags, Address activeFlag)
static uint32_t getBitWidth(const Expr *E)
#define EMIT_ARITH_OP(OP)
static CharUnits AlignOfType(QualType T, const ASTContext &ASTCtx, UnaryExprOrTypeTrait Kind)
static const Expr * stripDerivedToBaseCasts(const Expr *E)
static const Expr * stripCheckedDerivedToBaseCasts(const Expr *E)
static bool hasTrivialDefaultCtorParent(const FieldDecl *FD)
static bool initNeedsOverridenLoc(const CXXCtorInitializer *Init)
llvm::APSInt APSInt
Definition Compiler.cpp:26
const Expr * ignorePointerCastsAndParens(const Expr *E)
A more selective version of E->IgnoreParenCasts for tryEvaluateBuiltinObjectSize. This ignores some c...
Result
Implement __builtin_bit_cast and related operations.
llvm::SmallPtrSet< const ParmVarDecl *, 1 > FoundParams
bool VisitDeclRefExpr(const DeclRefExpr *E) override
a trap message and trap category.
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
const LValueBase getLValueBase() const
Definition APValue.cpp:1018
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:629
ArrayRef< LValuePathEntry > getLValuePath() const
Definition APValue.cpp:1038
APSInt & getInt()
Definition APValue.h:511
APValue & getStructField(unsigned i)
Definition APValue.h:674
const FieldDecl * getUnionField() const
Definition APValue.h:695
unsigned getStructNumFields() const
Definition APValue.h:661
APValue & getStructVirtualBase(unsigned i)
Definition APValue.h:679
bool isArray() const
Definition APValue.h:496
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1108
unsigned getArrayInitializedElts() const
Definition APValue.h:648
bool isFloat() const
Definition APValue.h:489
unsigned getStructNumBases() const
Definition APValue.h:657
unsigned getStructNumVirtualBases() const
Definition APValue.h:665
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1101
APValue & getUnionValue()
Definition APValue.h:699
APValue & getArrayFiller()
Definition APValue.h:640
bool isLValue() const
Definition APValue.h:493
bool isIndeterminate() const
Definition APValue.h:485
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1115
bool isMemberPointer() const
Definition APValue.h:499
bool isInt() const
Definition APValue.h:488
unsigned getArraySize() const
Definition APValue.h:652
bool isUnion() const
Definition APValue.h:498
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:129
bool isStruct() const
Definition APValue.h:497
bool isNullPointer() const
Definition APValue.cpp:1054
APFloat & getFloat()
Definition APValue.h:525
APValue & getStructBase(unsigned i)
Definition APValue.h:669
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
const LangOptions & getLangOpts() const
Definition ASTContext.h:985
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const VariableArrayType * getAsVariableArrayType(QualType T) const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4397
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4575
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4581
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4587
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition Expr.h:4594
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition Expr.h:6071
Represents a loop initializing the elements of an array.
Definition Expr.h:6018
llvm::APInt getArraySize() const
Definition Expr.h:6040
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:6033
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6038
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2765
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2794
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition ExprCXX.h:3010
uint64_t getValue() const
Definition ExprCXX.h:3058
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3836
QualType getElementType() const
Definition TypeBase.h:3848
Attr - This represents one attribute.
Definition Attr.h:46
Represents an attribute applied to a statement.
Definition Stmt.h:2215
Stmt * getSubStmt()
Definition Stmt.h:2251
ArrayRef< const Attr * > getAttrs() const
Definition Stmt.h:2247
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3525
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4082
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4215
Expr * getLHS() const
Definition Expr.h:4132
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4182
static bool isShiftOp(Opcode Opc)
Definition Expr.h:4170
static bool isCommaOp(Opcode Opc)
Definition Expr.h:4185
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4229
Expr * getRHS() const
Definition Expr.h:4134
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4159
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4218
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4223
Opcode getOpcode() const
Definition Expr.h:4127
static bool isBitwiseOp(Opcode Opc)
Definition Expr.h:4173
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6722
BreakStmt - This represents a break.
Definition Stmt.h:3147
Represents a C++2a __builtin_bit_cast(T, v) expression.
Definition ExprCXX.h:5529
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents binding an expression to a temporary.
Definition ExprCXX.h:1497
const Expr * getSubExpr() const
Definition ExprCXX.h:1519
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition ExprCXX.h:727
bool getValue() const
Definition ExprCXX.h:744
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1621
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1695
arg_range arguments()
Definition ExprCXX.h:1676
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1654
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1692
Represents a C++ constructor within a class.
Definition DeclCXX.h:2641
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3069
Represents a C++ base or member initializer.
Definition DeclCXX.h:2406
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1274
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1381
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1138
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2630
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2669
bool isArrayForm() const
Definition ExprCXX.h:2656
bool isGlobalDelete() const
Definition ExprCXX.h:2655
Represents a C++ destructor within a class.
Definition DeclCXX.h:2906
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition ExprCXX.h:485
Represents the code generated for an expanded expansion statement.
Definition StmtCXX.h:1028
ArrayRef< Stmt * > getInstantiations() const
Definition StmtCXX.h:1069
ArrayRef< Stmt * > getPreambleStmts() const
Definition StmtCXX.h:1073
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:136
DeclStmt * getBeginStmt()
Definition StmtCXX.h:164
DeclStmt * getLoopVarStmt()
Definition StmtCXX.h:170
DeclStmt * getEndStmt()
Definition StmtCXX.h:167
DeclStmt * getRangeStmt()
Definition StmtCXX.h:163
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition ExprCXX.h:1755
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1792
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2149
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2292
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2751
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2730
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2895
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2359
bool isArray() const
Definition ExprCXX.h:2468
QualType getAllocatedType() const
Definition ExprCXX.h:2438
std::optional< Expr * > getArraySize()
This might return std::nullopt even if isArray() returns true, since there might not be an array size...
Definition ExprCXX.h:2473
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2507
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2498
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2463
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2537
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition ExprCXX.h:4362
bool getValue() const
Definition ExprCXX.h:4385
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:772
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5194
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5234
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition DeclCXX.h:1255
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1681
capture_const_range captures() const
Definition DeclCXX.h:1106
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1744
A C++ reinterpret_cast expression (C++ [expr.reinterpret.cast]).
Definition ExprCXX.h:530
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:290
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:308
An expression "T()" which creates an rvalue of a non-class type T.
Definition ExprCXX.h:2200
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition ExprCXX.h:804
Represents the this expression in C++.
Definition ExprCXX.h:1158
A C++ throw-expression (C++ [except.throw]).
Definition ExprCXX.h:1212
const Expr * getSubExpr() const
Definition ExprCXX.h:1232
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:70
CompoundStmt * getTryBlock()
Definition StmtCXX.h:101
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition ExprCXX.h:852
bool isTypeOperand() const
Definition ExprCXX.h:888
QualType getTypeOperand(const ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition ExprCXX.cpp:167
Expr * getExprOperand() const
Definition ExprCXX.h:899
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
Definition ExprCXX.cpp:135
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h:1072
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1118
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2987
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3191
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3170
Expr * getCallee()
Definition Expr.h:3134
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3178
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3181
arg_range arguments()
Definition Expr.h:3239
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1631
CaseStmt - Represent a case statement.
Definition Stmt.h:1932
Stmt * getSubStmt()
Definition Stmt.h:2045
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3720
path_iterator path_begin()
Definition Expr.h:3790
CastKind getCastKind() const
Definition Expr.h:3764
llvm::iterator_range< path_iterator > path()
Path through the class hierarchy taken by casts between base and derived classes (see implementation ...
Definition Expr.h:3807
const FieldDecl * getTargetUnionField() const
Definition Expr.h:3814
path_iterator path_end()
Definition Expr.h:3791
Expr * getSubExpr()
Definition Expr.h:3770
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
unsigned getValue() const
Definition Expr.h:1649
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4892
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4928
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3355
QualType getElementType() const
Definition TypeBase.h:3365
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4344
QualType getComputationLHSType() const
Definition Expr.h:4378
QualType getComputationResultType() const
Definition Expr.h:4381
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3649
bool isFileScope() const
Definition Expr.h:3681
const Expr * getInitializer() const
Definition Expr.h:3677
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1752
body_range body()
Definition Stmt.h:1815
Stmt * body_back()
Definition Stmt.h:1820
Represents the specialization of a concept - evaluates to a prvalue of type bool.
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3874
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3950
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition Expr.h:1102
APValue getAPValueResult() const
Definition Expr.cpp:419
bool hasAPValueResult() const
Definition Expr.h:1177
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4501
ContinueStmt - This represents a continue.
Definition Stmt.h:3131
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition Expr.h:4763
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4853
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1290
ValueDecl * getDecl()
Definition Expr.h:1358
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1643
decl_range decls()
Definition Stmt.h:1691
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInvalidDecl() const
Definition DeclBase.h:596
bool hasAttr() const
Definition DeclBase.h:585
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
Stmt * getSubStmt()
Definition Stmt.h:2093
InitListExpr * getUpdater() const
Definition Expr.h:5986
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2844
Stmt * getBody()
Definition Stmt.h:2869
Expr * getCond()
Definition Stmt.h:2862
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
Recursively visit a statement or expression, by dispatching to Traverse*() based on the argument's dy...
const Expr * getBase() const
Definition Expr.h:6631
Represents a reference to emded data.
Definition Expr.h:5179
ChildElementIter< false > begin()
Definition Expr.h:5285
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition ExprCXX.h:3714
This represents one expression.
Definition Expr.h:113
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:85
bool isGLValue() const
Definition Expr.h:288
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3111
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:247
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3119
bool isPRValue() const
Definition Expr.h:286
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:285
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3722
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition Expr.cpp:3286
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:480
QualType getType() const
Definition Expr.h:145
An expression trait intrinsic.
Definition ExprCXX.h:3083
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6660
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4585
Represents a member of a struct/union/class.
Definition Decl.h:3295
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3531
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1595
llvm::APFloat getValue() const
Definition Expr.h:1686
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2900
Stmt * getInit()
Definition Stmt.h:2915
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1120
Stmt * getBody()
Definition Stmt.h:2944
Expr * getInc()
Definition Stmt.h:2943
Expr * getCond()
Definition Stmt.h:2942
DeclStmt * getConditionVariableDeclStmt()
If this ForStmt has a condition variable, return the faux DeclStmt associated with the creation of th...
Definition Stmt.h:2930
const Expr * getSubExpr() const
Definition Expr.h:1082
Represents a function declaration or definition.
Definition Decl.h:2059
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2928
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3268
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4246
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4234
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3806
QualType getReturnType() const
Definition Decl.h:2976
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2504
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4370
bool isUsableAsGlobalAllocationFunctionInConstantEvaluation(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions described in i...
Definition Decl.cpp:3470
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2512
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3870
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3188
Declaration of a template function.
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, llvm::FoldingSetInsertToken &InsertToken)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition Expr.h:4967
Represents a C11 generic selection.
Definition Expr.h:6232
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition Expr.h:6518
IfStmt - This represents an if/then/else.
Definition Stmt.h:2271
Stmt * getThen()
Definition Stmt.h:2360
Stmt * getInit()
Definition Stmt.h:2421
bool isNonNegatedConsteval() const
Definition Stmt.h:2456
Expr * getCond()
Definition Stmt.h:2348
bool isNegatedConsteval() const
Definition Stmt.h:2460
Stmt * getElse()
Definition Stmt.h:2369
DeclStmt * getConditionVariableDeclStmt()
If this IfStmt has a condition variable, return the faux DeclStmt associated with the creation of tha...
Definition Stmt.h:2404
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1068
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1751
const Expr * getSubExpr() const
Definition Expr.h:1763
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6107
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3602
Describes an C or C++ initializer list.
Definition Expr.h:5352
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5455
ArrayRef< Expr * > inits() const
Definition Expr.h:5405
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1972
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2098
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1433
bool isCompatibleWith(ClangABI Version) const
Implicit declaration of a temporary that was materialized by a MaterializeTemporaryExpr and lifetime-...
Definition DeclCXX.h:3337
const Stmt * getNamedLoopOrSwitch() const
If this is a named break/continue, get the loop or switch statement that this targets.
Definition Stmt.cpp:1535
A global _GUID constant.
Definition DeclCXX.h:4432
APValue & getAsAPValue() const
Get the value of this MSGuidDecl as an APValue.
Definition DeclCXX.cpp:3872
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4973
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4998
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4990
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition ExprCXX.h:5023
LifetimeExtendedTemporaryDecl * getLifetimeExtendedTemporaryDecl()
Definition ExprCXX.h:5013
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3408
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3491
Expr * getBase() const
Definition Expr.h:3485
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3767
This represents a decl that may have a name.
Definition Decl.h:275
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
Represents a C++ namespace alias.
Definition DeclCXX.h:3230
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp,...
Definition ExprObjC.h:219
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition ExprObjC.h:118
ObjCBoxedExpr - used for generalized expression boxing.
Definition ExprObjC.h:158
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition ExprObjC.h:341
ObjCEncodeExpr, used for @encode in Objective-C.
Definition ExprObjC.h:440
QualType getEncodedType() const
Definition ExprObjC.h:459
SourceLocation getAtLoc() const
Definition ExprObjC.h:454
bool isExpressibleAsConstantInitializer() const
Definition ExprObjC.h:67
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:83
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition Expr.h:2571
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2630
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2618
unsigned getNumComponents() const
Definition Expr.h:2626
Helper class for OffsetOfExpr.
Definition Expr.h:2465
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2523
@ Array
An index into an array.
Definition Expr.h:2470
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2519
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1198
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1248
Expr * getSelectedExpr() const
Definition ExprCXX.h:4692
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2226
const Expr * getSubExpr() const
Definition Expr.h:2243
Represents a parameter to a function.
Definition Decl.h:1820
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3408
QualType getPointeeType() const
Definition TypeBase.h:3418
[C99 6.4.2.2] - A predefined identifier such as func.
Definition Expr.h:2049
StringLiteral * getFunctionName()
Definition Expr.h:2093
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6854
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6902
ArrayRef< Expr * > semantics()
Definition Expr.h:6926
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8585
QualType withConst() const
Definition TypeBase.h:1175
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8501
bool isConstant(const ASTContext &Ctx) const
Definition TypeBase.h:1098
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8574
Represents a struct/union/class.
Definition Decl.h:4460
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7553
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3687
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
bool isSatisfied() const
Whether or not the requires clause is satisfied.
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3172
Expr * getRetValue()
Definition Stmt.h:3199
SourceLocation getLocation() const
Definition Expr.h:2199
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:593
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition Expr.h:4687
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4739
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4720
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4726
Represents an expression that computes the length of a parameter pack.
Definition ExprCXX.h:4494
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4568
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition Expr.h:5070
APValue EvaluateInContext(const ASTContext &Ctx, const Expr *DefaultExpr) const
Return the result of evaluating this SourceLocExpr in the specified (and possibly null) default argum...
Definition Expr.cpp:2313
Represents a C++11 static_assert declaration.
Definition DeclCXX.h:4165
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4639
CompoundStmt * getSubStmt()
Definition Expr.h:4656
Stmt - This represents one statement.
Definition Stmt.h:85
StmtClass getStmtClass() const
Definition Stmt.h:1505
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1819
unsigned getLength() const
Definition Expr.h:1944
uint32_t getCodeUnit(size_t I) const
Return the code unit at the given position.
Definition Expr.h:1906
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1194
unsigned getCharByteWidth() const
Definition Expr.h:1946
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4717
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1905
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2521
Expr * getCond()
Definition Stmt.h:2584
Stmt * getBody()
Definition Stmt.h:2596
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1186
Stmt * getInit()
Definition Stmt.h:2601
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2652
DeclStmt * getConditionVariableDeclStmt()
If this SwitchStmt has a condition variable, return the faux DeclStmt associated with the creation of...
Definition Stmt.h:2635
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3852
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3953
bool isUnion() const
Definition Decl.h:4063
A template argument list.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
A type trait used in the implementation of various C++11 and Library TR1 trait templates.
Definition ExprCXX.h:2900
bool getBoolValue() const
Definition ExprCXX.h:2961
bool isStoredAsComparisonResult() const
Definition ExprCXX.h:2957
const APValue & getAPValue() const
Definition ExprCXX.h:2966
bool isStoredAsBoolean() const
Definition ExprCXX.h:2953
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9110
bool isBooleanType() const
Definition TypeBase.h:9247
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:3145
bool isIncompleteArrayType() const
Definition TypeBase.h:8845
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isNothrowT() const
Definition Type.cpp:3329
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:749
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2549
bool isArrayType() const
Definition TypeBase.h:8837
bool isFunctionPointerType() const
Definition TypeBase.h:8805
bool isConstantMatrixType() const
Definition TypeBase.h:8905
bool isPointerType() const
Definition TypeBase.h:8738
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9154
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9404
bool isReferenceType() const
Definition TypeBase.h:8762
bool isEnumeralType() const
Definition TypeBase.h:8869
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9232
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9079
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
bool isAnyComplexType() const
Definition TypeBase.h:8873
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9170
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9290
bool isMemberPointerType() const
Definition TypeBase.h:8819
bool isAtomicType() const
Definition TypeBase.h:8930
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isStdByteType() const
Definition Type.cpp:3348
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9390
bool isPointerOrReferenceType() const
Definition TypeBase.h:8742
bool isFunctionType() const
Definition TypeBase.h:8734
bool isVectorType() const
Definition TypeBase.h:8877
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2437
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2998
bool isFloatingType() const
Definition Type.cpp:2421
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9337
bool isRecordType() const
Definition TypeBase.h:8865
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2695
bool hasBooleanRepresentation() const
Determine whether this type has a boolean representation – i.e., it is a boolean type,...
Definition Type.cpp:2476
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3697
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2669
QualType getArgumentType() const
Definition Expr.h:2712
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2738
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2701
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2288
Expr * getSubExpr() const
Definition Expr.h:2329
Opcode getOpcode() const
Definition Expr.h:2324
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2342
Represents C++ using-directive.
Definition DeclCXX.h:3125
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
QualType getType() const
Definition Decl.h:724
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5645
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:933
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1594
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1603
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1307
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1248
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2641
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1215
const Expr * getInit() const
Definition Decl.h:1392
const APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2557
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1275
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1382
Represents a GCC generic vector type.
Definition TypeBase.h:4289
unsigned getNumElements() const
Definition TypeBase.h:4304
QualType getElementType() const
Definition TypeBase.h:4303
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2709
Expr * getCond()
Definition Stmt.h:2761
DeclStmt * getConditionVariableDeclStmt()
If this WhileStmt has a condition variable, return the faux DeclStmt associated with the creation of ...
Definition Stmt.h:2797
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1247
Stmt * getBody()
Definition Stmt.h:2773
ArrayIndexScope(Compiler< Emitter > *Ctx, uint64_t Index)
Definition Compiler.cpp:222
A memory block, either on the stack or in the heap.
Definition InterpBlock.h:43
void invokeDtor()
Invokes the Destructor.
Compilation context for expressions.
Definition Compiler.h:119
llvm::SmallVector< InitLink > InitStack
Definition Compiler.h:506
bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E)
bool VisitCXXDeleteExpr(const CXXDeleteExpr *E)
bool VisitOffsetOfExpr(const OffsetOfExpr *E)
bool visitContinueStmt(const ContinueStmt *S)
bool VisitCharacterLiteral(const CharacterLiteral *E)
bool visitArrayElemInit(unsigned ElemIndex, const Expr *Init, OptPrimType InitT)
Pointer to the array(not the element!) must be on the stack when calling this.
bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E)
bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E)
bool visitInitializerPop(const Expr *E)
Similar, but will also pop the pointer.
bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
bool visitBool(const Expr *E)
Visits an expression and converts it to a boolean.
bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
PrimType classifyPrim(QualType Ty) const
Classifies a known primitive type.
Definition Compiler.h:297
bool VisitTypeTraitExpr(const TypeTraitExpr *E)
bool VisitLambdaExpr(const LambdaExpr *E)
bool VisitMemberExpr(const MemberExpr *E)
llvm::DenseMap< const OpaqueValueExpr *, unsigned > OpaqueExprs
OpaqueValueExpr to location mapping.
Definition Compiler.h:481
bool VisitBinaryOperator(const BinaryOperator *E)
bool visitCXXExpansionStmtInstantiation(const CXXExpansionStmtInstantiation *S)
template for (auto x : {1, 2}) {}
bool visitAttributedStmt(const AttributedStmt *S)
bool VisitPackIndexingExpr(const PackIndexingExpr *E)
bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
bool VisitCallExpr(const CallExpr *E)
std::optional< uint64_t > ArrayIndex
Current argument index. Needed to emit ArrayInitIndexExpr.
Definition Compiler.h:487
bool VisitPseudoObjectExpr(const PseudoObjectExpr *E)
bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E)
bool visitAPValueInitializer(const APValue &Val, SourceInfo Info, QualType T, bool IsCompleteClass=true)
const Function * getFunction(const FunctionDecl *FD)
Returns a function for the given FunctionDecl.
bool VisitFixedPointBinOp(const BinaryOperator *E)
bool VisitCastExpr(const CastExpr *E)
Definition Compiler.cpp:451
bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E)
bool VisitFixedPointUnaryOperator(const UnaryOperator *E)
bool VisitComplexUnaryOperator(const UnaryOperator *E)
llvm::DenseMap< const SwitchCase *, LabelTy > CaseMap
Definition Compiler.h:125
bool VisitBlockExpr(const BlockExpr *E)
bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E)
bool VisitLogicalBinOp(const BinaryOperator *E)
bool visitCompoundStmt(const CompoundStmt *S)
Context & Ctx
Current compilation context.
Definition Compiler.h:142
const VarDecl * InitializingDecl
Definition Compiler.h:504
bool visitDeclRef(const ValueDecl *D, const Expr *E)
Visit the given decl as if we have a reference to it.
bool visitBreakStmt(const BreakStmt *S)
bool visitExpr(const Expr *E, bool DestroyToplevelScope) override
bool visitForStmt(const ForStmt *S)
bool VisitDeclRefExpr(const DeclRefExpr *E)
bool VisitOpaqueValueExpr(const OpaqueValueExpr *E)
bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E)
bool visitAPValue(const APValue &Val, PrimType ValType, SourceInfo Info)
Visit an APValue.
bool VisitStmtExpr(const StmtExpr *E)
bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E)
bool VisitFixedPointLiteral(const FixedPointLiteral *E)
const FunctionDecl * CompilingFunction
Definition Compiler.h:517
bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E)
VarCreationState visitVarDecl(const VarDecl *VD, const Expr *Init, bool Toplevel=false)
Creates and initializes a variable from the given decl.
VariableScope< Emitter > * VarScope
Current scope.
Definition Compiler.h:484
bool visitDeclAndReturn(const VarDecl *VD, const Expr *Init, bool ConstantContext) override
Toplevel visitDeclAndReturn().
bool VisitCXXNewExpr(const CXXNewExpr *E)
bool VisitCompoundAssignOperator(const CompoundAssignOperator *E)
bool visit(const Expr *E) override
Evaluates an expression and places the result on the stack.
bool delegate(const Expr *E)
Just pass evaluation on to E.
bool visitLValueExpr(const Expr *E, bool DestroyToplevelScope) override
bool discard(const Expr *E)
Evaluates an expression for side effects and discards the result.
bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
CaseMap CaseLabels
Switch case mapping.
Definition Compiler.h:513
Record * getRecord(QualType Ty)
Returns a record from a record or pointer type.
const RecordType * getRecordTy(QualType Ty)
Returns a record type from a record or pointer type.
bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E)
bool visitInitList(ArrayRef< const Expr * > Inits, const Expr *ArrayFiller, const Expr *E)
bool VisitSizeOfPackExpr(const SizeOfPackExpr *E)
bool VisitPredefinedExpr(const PredefinedExpr *E)
bool VisitSourceLocExpr(const SourceLocExpr *E)
bool visitDeclStmt(const DeclStmt *DS, bool EvaluateConditionDecl=false)
bool emitCleanup()
Emits scope cleanup instructions.
bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E)
bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E)
bool visitInitializer(const Expr *E)
Compiles an initializer.
bool visitDtorCall(const VarDecl *VD, const APValue &Value) override
const Expr * SourceLocDefaultExpr
DefaultInit- or DefaultArgExpr, needed for SourceLocExpr.
Definition Compiler.h:490
bool VisitObjCArrayLiteral(const ObjCArrayLiteral *E)
UnsignedOrNone OptLabelTy
Definition Compiler.h:124
bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E)
bool VisitPointerArithBinOp(const BinaryOperator *E)
Perform addition/subtraction of a pointer and an integer or subtraction of two pointers.
bool visitCallArgs(ArrayRef< const Expr * > Args, const FunctionDecl *FuncDecl, bool Activate, bool IsOperatorCall)
bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E)
bool visitDefaultStmt(const DefaultStmt *S)
bool VisitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E)
bool visitWithSubstitutions(const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This, const Expr *Condition) override
Evaluate the Condition as if it was in the body of Callee.
typename Emitter::LabelTy LabelTy
Definition Compiler.h:122
VarCreationState visitDecl(const VarDecl *VD)
bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E)
bool visitStmt(const Stmt *S)
bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E)
bool VisitVectorUnaryOperator(const UnaryOperator *E)
bool VisitCXXConstructExpr(const CXXConstructExpr *E)
bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
bool VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E)
bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E)
bool VisitRecoveryExpr(const RecoveryExpr *E)
bool VisitRequiresExpr(const RequiresExpr *E)
bool Initializing
Flag inidicating if we're initializing an already created variable.
Definition Compiler.h:503
bool visitReturnStmt(const ReturnStmt *RS)
bool VisitCXXThrowExpr(const CXXThrowExpr *E)
bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
bool VisitChooseExpr(const ChooseExpr *E)
bool visitFunc(const FunctionDecl *F) override
bool visitCXXForRangeStmt(const CXXForRangeStmt *S)
bool visitCaseStmt(const CaseStmt *S)
bool VisitComplexBinOp(const BinaryOperator *E)
llvm::DenseMap< const ValueDecl *, Scope::Local > Locals
Variable to storage mapping.
Definition Compiler.h:478
bool VisitAbstractConditionalOperator(const AbstractConditionalOperator *E)
bool VisitCXXTypeidExpr(const CXXTypeidExpr *E)
UnsignedOrNone allocateTemporary(const Expr *E)
bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinID)
bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E)
OptPrimType ReturnType
Type of the expression returned by the function.
Definition Compiler.h:510
bool VisitUnaryOperator(const UnaryOperator *E)
bool VisitFloatCompoundAssignOperator(const CompoundAssignOperator *E)
OptPrimType classify(const Expr *E) const
Definition Compiler.h:291
llvm::SmallVector< LabelInfo > LabelInfoStack
Stack of label information for loops and switch statements.
Definition Compiler.h:515
bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
bool visitDoStmt(const DoStmt *S)
bool VisitIntegerLiteral(const IntegerLiteral *E)
bool VisitInitListExpr(const InitListExpr *E)
bool VisitVectorBinOp(const BinaryOperator *E)
bool VisitStringLiteral(const StringLiteral *E)
bool VisitParenExpr(const ParenExpr *E)
bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E)
bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E)
bool VisitPointerCompoundAssignOperator(const CompoundAssignOperator *E)
bool DiscardResult
Flag indicating if return value is to be discarded.
Definition Compiler.h:493
bool VisitEmbedExpr(const EmbedExpr *E)
UnsignedOrNone allocateLocal(DeclOrExpr Decl, QualType Ty=QualType(), ScopeKind=ScopeKind::Block)
Allocates a space storing a local given its type.
bool VisitConvertVectorExpr(const ConvertVectorExpr *E)
bool VisitCXXThisExpr(const CXXThisExpr *E)
bool VisitConstantExpr(const ConstantExpr *E)
bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
bool visitSwitchStmt(const SwitchStmt *S)
bool VisitCXXUuidofExpr(const CXXUuidofExpr *E)
bool VisitExprWithCleanups(const ExprWithCleanups *E)
bool visitAsLValue(const Expr *E)
unsigned allocateLocalPrimitive(DeclOrExpr Decl, PrimType Ty, bool IsConst, bool IsVolatile=false, ScopeKind SC=ScopeKind::Block)
Creates a local primitive value.
bool visitWhileStmt(const WhileStmt *S)
bool visitIfStmt(const IfStmt *IS)
bool VisitAddrLabelExpr(const AddrLabelExpr *E)
bool canClassify(const Expr *E) const
Definition Compiler.h:293
bool VisitFloatingLiteral(const FloatingLiteral *E)
Program & P
Program to link to.
Definition Compiler.h:144
bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E)
bool VisitGNUNullExpr(const GNUNullExpr *E)
bool VisitImaginaryLiteral(const ImaginaryLiteral *E)
bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E)
bool visitCXXTryStmt(const CXXTryStmt *S)
static bool isUnevaluatedBuiltin(unsigned ID)
Unevaluated builtins don't get their arguments put on the stack automatically.
Definition Context.cpp:821
static bool shouldBeGloballyIndexed(const ValueDecl *VD)
Returns whether we should create a global variable for the given ValueDecl.
Definition Context.h:166
Scope used to handle temporaries in toplevel variable declarations.
Definition Compiler.cpp:289
DeclScope(Compiler< Emitter > *Ctx, const VarDecl *VD)
Definition Compiler.cpp:291
Wrapper around fixed point types.
Definition FixedPoint.h:23
static FixedPoint zero(llvm::FixedPointSemantics Sem)
Definition FixedPoint.h:36
If a Floating is constructed from Memory, it DOES NOT OWN THAT MEMORY.
Definition Floating.h:35
bool singleWord() const
Definition Floating.h:107
Bytecode function.
Definition Function.h:98
bool hasThisPointer() const
Definition Function.h:225
bool hasRVO() const
Checks if the first argument is a RVO pointer.
Definition Function.h:155
InitLinkScope(Compiler< Emitter > *Ctx, InitLink &&Link)
Definition Compiler.cpp:257
Compiler< Emitter > * Ctx
Definition Compiler.cpp:264
InitStackScope(Compiler< Emitter > *Ctx, bool Active)
Definition Compiler.cpp:269
When generating code for e.g.
Definition Compiler.cpp:426
LocOverrideScope(Compiler< Emitter > *Ctx, SourceInfo NewValue, bool Enabled=true)
Definition Compiler.cpp:428
Generic scope for local variables.
Definition Compiler.cpp:113
UnsignedOrNone Idx
Index of the scope in the chain.
Definition Compiler.cpp:216
~LocalScope() override
Emit a Destroy op for this scope.
Definition Compiler.cpp:119
bool destroyLocals(const Expr *E=nullptr) override
Explicit destruction of local variables.
Definition Compiler.cpp:126
bool emitDestructors(const Expr *E=nullptr) override
Definition Compiler.cpp:162
void removeIfStoredOpaqueValue(const Scope::Local &Local)
Definition Compiler.cpp:208
void addLocal(Scope::Local Local) override
Definition Compiler.cpp:138
void forceInit() override
Force-initialize this scope.
Definition Compiler.cpp:154
LocalScope(Compiler< Emitter > *Ctx, ScopeKind Kind=ScopeKind::Block)
Definition Compiler.cpp:115
Sets the context for break/continue statements.
Definition Compiler.cpp:365
typename Compiler< Emitter >::LabelTy LabelTy
Definition Compiler.cpp:367
typename Compiler< Emitter >::OptLabelTy OptLabelTy
Definition Compiler.cpp:368
typename Compiler< Emitter >::LabelInfo LabelInfo
Definition Compiler.cpp:369
LoopScope(Compiler< Emitter > *Ctx, const Stmt *Name, LabelTy BreakLabel, LabelTy ContinueLabel)
Definition Compiler.cpp:371
PrimType value_or(PrimType PT) const
Definition PrimType.h:88
Scope used to handle initialization methods.
Definition Compiler.cpp:309
OptionScope(Compiler< Emitter > *Ctx, bool NewDiscardResult, bool NewInitializing, bool NewToLValue)
Root constructor, compiling or discarding primitives.
Definition Compiler.cpp:312
Context to manage declaration lifetimes.
Definition Program.h:141
Structure/Class descriptor.
Definition Record.h:25
bool isUnion() const
Checks if the record is a union.
Definition Record.h:74
const Field * getField(unsigned I) const
Definition Record.h:100
const Base * getBaseOrNull(const RecordDecl *RD) const
Definition Record.cpp:66
bool hasTrivialDtor() const
Returns true for anonymous unions and records with no destructor or for those with a trivial destruct...
Definition Record.cpp:44
const Base * findVirtualBase(const RecordDecl *RD) const
Returns a virtual base descriptor.
Definition Record.cpp:85
Describes a scope block.
Definition Function.h:35
Describes the statement/declaration an opcode was generated from.
Definition Source.h:77
const Expr * asExpr() const
Definition Source.h:92
SourceLocScope(Compiler< Emitter > *Ctx, const Expr *DefaultExpr)
Definition Compiler.cpp:236
typename Compiler< Emitter >::LabelTy LabelTy
Definition Compiler.cpp:393
typename Compiler< Emitter >::OptLabelTy OptLabelTy
Definition Compiler.cpp:394
typename Compiler< Emitter >::LabelInfo LabelInfo
Definition Compiler.cpp:396
typename Compiler< Emitter >::CaseMap CaseMap
Definition Compiler.cpp:395
SwitchScope(Compiler< Emitter > *Ctx, const Stmt *Name, CaseMap &&CaseLabels, LabelTy BreakLabel, OptLabelTy DefaultLabel)
Definition Compiler.cpp:398
Scope chain managing the variable lifetimes.
Definition Compiler.cpp:55
void addForScopeKind(const Scope::Local &Local, ScopeKind Kind)
Like addExtended, but adds to the nearest scope of the given kind.
Definition Compiler.cpp:70
bool LocalsAlwaysEnabled
Whether locals added to this scope are enabled by default.
Definition Compiler.cpp:102
Compiler< Emitter > * Ctx
Compiler instance.
Definition Compiler.cpp:106
virtual bool emitDestructors(const Expr *E=nullptr)
Definition Compiler.cpp:93
VariableScope(Compiler< Emitter > *Ctx, ScopeKind Kind=ScopeKind::Block)
Definition Compiler.cpp:57
virtual bool destroyLocals(const Expr *E=nullptr)
Definition Compiler.cpp:94
virtual void addLocal(Scope::Local Local)
Definition Compiler.cpp:66
VariableScope * Parent
Link to the parent scope.
Definition Compiler.cpp:108
ScopeKind getKind() const
Definition Compiler.cpp:97
VariableScope * getParent() const
Definition Compiler.cpp:96
bool Sub(InterpState &S, CodePtr OpPC)
Definition Interp.h:447
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1524
static llvm::RoundingMode getRoundingMode(FPOptions FPO)
constexpr bool isSignedType(PrimType T)
Definition PrimType.h:59
bool Div(InterpState &S, CodePtr OpPC)
1) Pops the RHS from the stack.
Definition Interp.h:792
constexpr bool isPtrType(PrimType T)
Definition PrimType.h:55
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition PrimType.h:213
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3232
constexpr bool isIntegerOrBoolType(PrimType T)
Definition PrimType.h:52
llvm::APFloat APFloat
Definition Floating.h:27
bool InitScope(InterpState &S, uint32_t I)
Definition Interp.h:2860
static void discard(InterpStack &Stk, PrimType T)
static bool isSideEffectFree(const Expr *E)
Check if E has side-effects.
Definition Compiler.cpp:44
llvm::APInt APInt
Definition FixedPoint.h:19
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1531
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:34
static std::optional< bool > getBoolValue(const Expr *E)
Definition Compiler.cpp:31
static bool Activate(InterpState &S)
Definition Interp.h:2296
bool Init(InterpState &S, CodePtr OpPC)
Definition Interp.h:2413
bool Mul(InterpState &S, CodePtr OpPC)
Definition Interp.h:501
size_t primSize(PrimType Type)
Returns the size of a primitive type in bytes.
Definition PrimType.cpp:24
bool Inc(InterpState &S, CodePtr OpPC, bool CanOverflow)
1) Pops a pointer from the stack 2) Load the value from the pointer 3) Writes the value increased by ...
Definition Interp.h:986
bool Add(InterpState &S, CodePtr OpPC)
Definition Interp.h:418
llvm::BitVector collectNonNullArgs(const FunctionDecl *F, ArrayRef< const Expr * > Args)
constexpr bool isIntegerType(PrimType T)
Definition PrimType.h:53
llvm::APSInt APSInt
Definition FixedPoint.h:20
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool hasSpecificAttr(const Container &container)
@ Success
Annotation was successful.
Definition Parser.h:65
@ Link
'link' clause, allowed on 'declare' construct.
DynamicRecursiveASTVisitorBase< true > ConstDynamicRecursiveASTVisitor
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
@ SD_Static
Static storage duration.
Definition Specifiers.h:342
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:339
@ Result
The result type of a method or function.
Definition TypeBase.h:906
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
U cast(CodeGen::Address addr)
Definition Address.h:327
int const char * function
Definition c++config.h:31
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
#define true
Definition stdbool.h:25
llvm::APSInt getIntValue() const
Get the constant integer value used by this variable to represent the comparison category result type...
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:666
A quantity in bits.
const ValueDecl * asValueDecl() const
Definition DeclOrExpr.h:34
const Expr * asExpr() const
Definition DeclOrExpr.h:32
Describes a memory block created by an allocation site.
Definition Descriptor.h:122
unsigned getNumElems() const
Returns the number of elements stored in the block.
Definition Descriptor.h:246
bool isPrimitive() const
Checks if the descriptor is of a primitive.
Definition Descriptor.h:260
QualType getElemQualType() const
bool hasTrivialDtor() const
Whether variables of this descriptor need their destructor called or not.
bool isCompositeArray() const
Checks if the descriptor is of an array of composites.
Definition Descriptor.h:253
QualType getType() const
const Descriptor *const ElemDesc
Descriptor of the array element.
Definition Descriptor.h:148
bool isPrimitiveArray() const
Checks if the descriptor is of an array of primitives.
Definition Descriptor.h:251
PrimType getPrimType() const
Definition Descriptor.h:231
bool isRecord() const
Checks if the descriptor is of a record.
Definition Descriptor.h:265
const Record *const ElemRecord
Pointer to the record, if block contains records.
Definition Descriptor.h:146
bool isArray() const
Checks if the descriptor is of an array.
Definition Descriptor.h:263
Descriptor used for global variables.
Definition Descriptor.h:49
Information about a local's storage.
Definition Function.h:38
State encapsulating if a the variable creation has been successful, unsuccessful, or no variable has ...
Definition Compiler.h:104
static VarCreationState NotCreated()
Definition Compiler.h:108