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