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