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