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