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