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