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 between vectors and integers of the same same size.
785 if (ETy->isVectorType() || SubExprTy->isVectorType())
786 return this->emitBuiltinBitCast(E);
787
788 OptPrimType ToT = classify(E->getType());
789 if (!FromT || !ToT)
790 return false;
791
792 assert(isPtrType(*FromT));
793 assert(isPtrType(*ToT));
794 bool SrcIsVoidPtr = SubExprTy->isVoidPointerType();
795 if (FromT == ToT) {
796 if (E->getType()->isVoidPointerType() &&
797 !SubExprTy->isFunctionPointerType()) {
798 return this->delegate(SubExpr);
799 }
800
801 if (!this->visit(SubExpr))
802 return false;
803 if (!this->emitCheckBitCast(ETy->getPointeeType().getTypePtr(),
804 SrcIsVoidPtr, E))
805 return false;
806
807 if (E->getType()->isFunctionPointerType() ||
808 SubExprTy->isFunctionPointerType()) {
809 return this->emitFnPtrCast(E);
810 }
811 if (FromT == PT_Ptr)
812 return this->emitPtrPtrCast(SubExprTy->isVoidPointerType(),
813 E->getType().getTypePtr(), E);
814 return true;
815 }
816
817 if (!this->visit(SubExpr))
818 return false;
819 return this->emitDecayPtr(*FromT, *ToT, E);
820 }
821 case CK_IntegralToBoolean:
822 case CK_FixedPointToBoolean: {
823 if (E->getType()->isVectorType())
824 return this->emitVectorConversion(E->getSubExpr(), E);
825 // HLSL uses this to cast to one-element vectors.
826 OptPrimType FromT = classify(SubExpr->getType());
827 if (!FromT)
828 return false;
829
830 if (const auto *IL = dyn_cast<IntegerLiteral>(SubExpr))
831 return this->emitConst(IL->getValue(), E);
832 if (!this->visit(SubExpr))
833 return false;
834 return this->emitCast(*FromT, classifyPrim(E), E);
835 }
836
837 case CK_IntegralCast:
838 if (E->getType()->isVectorType())
839 return this->emitVectorConversion(E->getSubExpr(), E);
840 [[fallthrough]];
841 case CK_BooleanToSignedIntegral: {
842 OptPrimType FromT = classify(SubExpr->getType());
843 OptPrimType ToT = classify(E->getType());
844 if (!FromT || !ToT)
845 return false;
846
847 // Try to emit a casted known constant value directly.
848 if (const auto *IL = dyn_cast<IntegerLiteral>(SubExpr)) {
849 if (ToT != PT_IntAP && ToT != PT_IntAPS && FromT != PT_IntAP &&
850 FromT != PT_IntAPS && !E->getType()->isEnumeralType())
851 return this->emitConst(APSInt(IL->getValue(), !isSignedType(*FromT)),
852 E);
853 if (!this->emitConst(IL->getValue(), SubExpr))
854 return false;
855 } else {
856 if (!this->visit(SubExpr))
857 return false;
858 }
859
860 // Possibly diagnose casts to enum types if the target type does not
861 // have a fixed size.
862 if (Ctx.getLangOpts().CPlusPlus && E->getType()->isEnumeralType()) {
863 const auto *ED = E->getType()->castAsEnumDecl();
864 if (!ED->isFixed()) {
865 if (!this->emitCheckEnumValue(*FromT, ED, E))
866 return false;
867 }
868 }
869
870 if (ToT == PT_IntAP) {
871 if (!this->emitCastAP(*FromT, Ctx.getBitWidth(E->getType()), E))
872 return false;
873 } else if (ToT == PT_IntAPS) {
874 if (!this->emitCastAPS(*FromT, Ctx.getBitWidth(E->getType()), E))
875 return false;
876 } else {
877 if (FromT == ToT)
878 return true;
879 if (!this->emitCast(*FromT, *ToT, E))
880 return false;
881 }
882 if (E->getCastKind() == CK_BooleanToSignedIntegral)
883 return this->emitNeg(*ToT, E);
884 return true;
885 }
886
887 case CK_PointerToBoolean:
888 if (!this->visit(SubExpr))
889 return false;
890 return this->emitIsNonNullPtr(E);
891
892 case CK_MemberPointerToBoolean:
893 if (!this->visit(SubExpr))
894 return false;
895 return this->emitIsNonNullMemberPtr(E);
896
897 case CK_IntegralComplexToBoolean:
898 case CK_FloatingComplexToBoolean: {
899 if (!this->visit(SubExpr))
900 return false;
901 return this->emitComplexBoolCast(SubExpr);
902 }
903
904 case CK_IntegralComplexToReal:
905 case CK_FloatingComplexToReal:
906 return this->emitComplexReal(SubExpr);
907
908 case CK_IntegralRealToComplex:
909 case CK_FloatingRealToComplex: {
910 // We're creating a complex value here, so we need to
911 // allocate storage for it.
912 if (!Initializing) {
913 UnsignedOrNone LocalIndex = allocateTemporary(E);
914 if (!LocalIndex)
915 return false;
916 if (!this->emitGetPtrLocal(*LocalIndex, E))
917 return false;
918 }
919
920 PrimType T = classifyPrim(SubExpr->getType());
921 // Init the complex value to {SubExpr, 0}.
922 if (!this->visitArrayElemInit(0, SubExpr, T))
923 return false;
924 // Zero-init the second element.
925 if (!this->visitZeroInitializer(T, SubExpr->getType(), SubExpr))
926 return false;
927 return this->emitInitElem(T, 1, SubExpr);
928 }
929
930 case CK_IntegralComplexCast:
931 case CK_FloatingComplexCast:
932 case CK_IntegralComplexToFloatingComplex:
933 case CK_FloatingComplexToIntegralComplex: {
934 assert(E->getType()->isAnyComplexType());
935 assert(SubExpr->getType()->isAnyComplexType());
936 if (!Initializing) {
937 UnsignedOrNone LocalIndex = allocateLocal(E);
938 if (!LocalIndex)
939 return false;
940 if (!this->emitGetPtrLocal(*LocalIndex, E))
941 return false;
942 }
943
944 // Location for the SubExpr.
945 // Since SubExpr is of complex type, visiting it results in a pointer
946 // anyway, so we just create a temporary pointer variable.
947 unsigned SubExprOffset =
948 allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
949 if (!this->visit(SubExpr))
950 return false;
951 if (!this->emitSetLocal(PT_Ptr, SubExprOffset, E))
952 return false;
953
954 PrimType SourceElemT = classifyComplexElementType(SubExpr->getType());
955 QualType DestElemType =
956 E->getType()->getAs<ComplexType>()->getElementType();
957 PrimType DestElemT = classifyPrim(DestElemType);
958 // Cast both elements individually.
959 for (unsigned I = 0; I != 2; ++I) {
960 if (!this->emitGetLocal(PT_Ptr, SubExprOffset, E))
961 return false;
962 if (!this->emitArrayElemPop(SourceElemT, I, E))
963 return false;
964
965 // Do the cast.
966 if (!this->emitPrimCast(SourceElemT, DestElemT, DestElemType, E))
967 return false;
968
969 // Save the value.
970 if (!this->emitInitElem(DestElemT, I, E))
971 return false;
972 }
973 return true;
974 }
975
976 case CK_VectorSplat: {
977 assert(!canClassify(E->getType()));
978 assert(E->getType()->isVectorType());
979
980 if (!canClassify(SubExpr->getType()))
981 return false;
982
983 if (!Initializing) {
984 UnsignedOrNone LocalIndex = allocateLocal(E);
985 if (!LocalIndex)
986 return false;
987 if (!this->emitGetPtrLocal(*LocalIndex, E))
988 return false;
989 }
990
991 const auto *VT = E->getType()->getAs<VectorType>();
992 PrimType ElemT = classifyPrim(SubExpr->getType());
993 unsigned ElemOffset =
994 allocateLocalPrimitive(SubExpr, ElemT, /*IsConst=*/true);
995
996 // Prepare a local variable for the scalar value.
997 if (!this->visit(SubExpr))
998 return false;
999 if (classifyPrim(SubExpr) == PT_Ptr && !this->emitLoadPop(ElemT, E))
1000 return false;
1001
1002 if (!this->emitSetLocal(ElemT, ElemOffset, E))
1003 return false;
1004
1005 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
1006 if (!this->emitGetLocal(ElemT, ElemOffset, E))
1007 return false;
1008 if (!this->emitInitElem(ElemT, I, E))
1009 return false;
1010 }
1011
1012 return true;
1013 }
1014
1015 case CK_HLSLVectorTruncation: {
1016 assert(SubExpr->getType()->isVectorType());
1017 if (OptPrimType ResultT = classify(E)) {
1018 assert(!DiscardResult);
1019 // Result must be either a float or integer. Take the first element.
1020 if (!this->visit(SubExpr))
1021 return false;
1022 return this->emitArrayElemPop(*ResultT, 0, E);
1023 }
1024 // Otherwise, this truncates from one vector type to another.
1025 assert(E->getType()->isVectorType());
1026
1027 if (!Initializing) {
1028 UnsignedOrNone LocalIndex = allocateTemporary(E);
1029 if (!LocalIndex)
1030 return false;
1031 if (!this->emitGetPtrLocal(*LocalIndex, E))
1032 return false;
1033 }
1034 unsigned ToSize = E->getType()->getAs<VectorType>()->getNumElements();
1035 assert(SubExpr->getType()->getAs<VectorType>()->getNumElements() > ToSize);
1036 if (!this->visit(SubExpr))
1037 return false;
1038 return this->emitCopyArray(classifyVectorElementType(E->getType()), 0, 0,
1039 ToSize, E);
1040 };
1041
1042 case CK_IntegralToFixedPoint: {
1043 if (!this->visit(SubExpr))
1044 return false;
1045
1046 auto Sem =
1047 Ctx.getASTContext().getFixedPointSemantics(E->getType()).toOpaqueInt();
1048 if (!this->emitCastIntegralFixedPoint(classifyPrim(SubExpr->getType()), Sem,
1049 E))
1050 return false;
1051 if (DiscardResult)
1052 return this->emitPopFixedPoint(E);
1053 return true;
1054 }
1055 case CK_FloatingToFixedPoint: {
1056 if (!this->visit(SubExpr))
1057 return false;
1058
1059 auto Sem =
1060 Ctx.getASTContext().getFixedPointSemantics(E->getType()).toOpaqueInt();
1061 if (!this->emitCastFloatingFixedPoint(Sem, E))
1062 return false;
1063 if (DiscardResult)
1064 return this->emitPopFixedPoint(E);
1065 return true;
1066 }
1067 case CK_FixedPointToFloating: {
1068 if (!this->visit(SubExpr))
1069 return false;
1070 const auto *TargetSemantics = &Ctx.getFloatSemantics(E->getType());
1071 if (!this->emitCastFixedPointFloating(TargetSemantics, E))
1072 return false;
1073 if (DiscardResult)
1074 return this->emitPopFloat(E);
1075 return true;
1076 }
1077 case CK_FixedPointToIntegral: {
1078 if (!this->visit(SubExpr))
1079 return false;
1080 PrimType IntegralT = classifyPrim(E->getType());
1081 if (!this->emitCastFixedPointIntegral(IntegralT, E))
1082 return false;
1083 if (DiscardResult)
1084 return this->emitPop(IntegralT, E);
1085 return true;
1086 }
1087 case CK_FixedPointCast: {
1088 if (!this->visit(SubExpr))
1089 return false;
1090 auto Sem =
1091 Ctx.getASTContext().getFixedPointSemantics(E->getType()).toOpaqueInt();
1092 if (!this->emitCastFixedPoint(Sem, E))
1093 return false;
1094 if (DiscardResult)
1095 return this->emitPopFixedPoint(E);
1096 return true;
1097 }
1098
1099 case CK_ToVoid:
1100 return discard(SubExpr);
1101
1102 case CK_Dynamic:
1103 llvm_unreachable("CXXDynamicCastExpr has its own function");
1104
1105 case CK_LValueBitCast:
1106 if (!this->emitInvalidCast(CastKind::ReinterpretLike, /*Fatal=*/false, E))
1107 return false;
1108 return this->delegate(SubExpr);
1109
1110 case CK_HLSLArrayRValue: {
1111 // Non-decaying array rvalue cast - creates an rvalue copy of an lvalue
1112 // array, similar to LValueToRValue for composite types.
1113 if (!Initializing) {
1114 UnsignedOrNone LocalIndex = allocateLocal(E);
1115 if (!LocalIndex)
1116 return false;
1117 if (!this->emitGetPtrLocal(*LocalIndex, E))
1118 return false;
1119 }
1120 if (!this->visit(SubExpr))
1121 return false;
1122 return this->emitMemcpy(E);
1123 }
1124
1125 case CK_HLSLMatrixTruncation: {
1126 assert(SubExpr->getType()->isConstantMatrixType());
1127 if (OptPrimType ResultT = classify(E)) {
1128 assert(!DiscardResult);
1129 // Result must be either a float or integer. Take the first element.
1130 if (!this->visit(SubExpr))
1131 return false;
1132 return this->emitArrayElemPop(*ResultT, 0, E);
1133 }
1134 // Otherwise, this truncates to a a constant matrix type.
1135 assert(E->getType()->isConstantMatrixType());
1136
1137 if (!Initializing) {
1138 UnsignedOrNone LocalIndex = allocateTemporary(E);
1139 if (!LocalIndex)
1140 return false;
1141 if (!this->emitGetPtrLocal(*LocalIndex, E))
1142 return false;
1143 }
1144 unsigned ToSize =
1145 E->getType()->getAs<ConstantMatrixType>()->getNumElementsFlattened();
1146 if (!this->visit(SubExpr))
1147 return false;
1148 return this->emitCopyArray(classifyMatrixElementType(SubExpr->getType()), 0,
1149 0, ToSize, E);
1150 }
1151
1152 case CK_HLSLAggregateSplatCast: {
1153 // Aggregate splat cast: convert a scalar value to one of an aggregate type
1154 // by replicating and casting the scalar to every element of the destination
1155 // aggregate (vector, matrix, array, or struct).
1156 assert(canClassify(SubExpr->getType()));
1157
1158 if (!Initializing) {
1159 UnsignedOrNone LocalIndex = allocateLocal(E);
1160 if (!LocalIndex)
1161 return false;
1162 if (!this->emitGetPtrLocal(*LocalIndex, E))
1163 return false;
1164 }
1165
1166 // The scalar to be splatted is stored in a local to be repeatedly loaded
1167 // once for every scalar element of the destination.
1168 PrimType SrcElemT = classifyPrim(SubExpr->getType());
1169 unsigned SrcOffset =
1170 allocateLocalPrimitive(SubExpr, SrcElemT, /*IsConst=*/true);
1171
1172 if (!this->visit(SubExpr))
1173 return false;
1174 if (!this->emitSetLocal(SrcElemT, SrcOffset, E))
1175 return false;
1176
1177 // Recursively splat the scalar into every element of the destination.
1178 return emitHLSLAggregateSplat(SrcElemT, SrcOffset, E->getType(), E);
1179 }
1180
1181 case CK_HLSLElementwiseCast: {
1182 // Elementwise cast: flatten the elements of one aggregate source type and
1183 // store to a destination scalar or aggregate type of the same or fewer
1184 // number of elements. Casts are inserted element-wise to convert each
1185 // source scalar element to its corresponding destination scalar element.
1186 QualType SrcType = SubExpr->getType();
1187 QualType DestType = E->getType();
1188
1189 if (OptPrimType DestT = classify(DestType)) {
1190 // When the destination is a scalar, we only need the first scalar
1191 // element of the source.
1192 unsigned SrcPtrOffset =
1193 allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
1194 if (!this->visit(SubExpr))
1195 return false;
1196 if (!this->emitSetLocal(PT_Ptr, SrcPtrOffset, E))
1197 return false;
1198
1200 if (!emitHLSLFlattenAggregate(SrcType, SrcPtrOffset, Elements, 1, E))
1201 return false;
1202 if (Elements.empty())
1203 return false;
1204
1205 const HLSLFlatElement &Src = Elements[0];
1206 if (!this->emitGetLocal(Src.Type, Src.LocalOffset, E))
1207 return false;
1208 return this->emitPrimCast(Src.Type, *DestT, DestType, E);
1209 }
1210
1211 if (!Initializing) {
1212 UnsignedOrNone LocalIndex = allocateLocal(E);
1213 if (!LocalIndex)
1214 return false;
1215 if (!this->emitGetPtrLocal(*LocalIndex, E))
1216 return false;
1217 }
1218
1219 unsigned SrcOffset =
1220 allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
1221 if (!this->visit(SubExpr))
1222 return false;
1223 if (!this->emitSetLocal(PT_Ptr, SrcOffset, E))
1224 return false;
1225
1226 // Only flatten as many source elements as the destination requires.
1227 unsigned ElemCount = countHLSLFlatElements(DestType);
1228
1230 Elements.reserve(ElemCount);
1231 if (!emitHLSLFlattenAggregate(SrcType, SrcOffset, Elements, ElemCount, E))
1232 return false;
1233
1234 // Sema is expected to reject an elementwise cast whose source has fewer
1235 // scalar elements than the destination.
1236 assert(Elements.size() == ElemCount &&
1237 "Source type has fewer scalar elements than the destination type");
1238
1239 return emitHLSLConstructAggregate(DestType, Elements, E);
1240 }
1241
1242 case CK_ToUnion: {
1243 const FieldDecl *UnionField = E->getTargetUnionField();
1244 const Record *R = this->getRecord(E->getType());
1245 assert(R);
1246 const Record::Field *RF = R->getField(UnionField);
1247
1248 if (OptPrimType PT = RF->T) {
1249 if (!this->visit(SubExpr))
1250 return false;
1251 if (RF->isBitField())
1252 return this->emitInitBitFieldActivate(*PT, RF->Offset, RF->bitWidth(),
1253 E);
1254 return this->emitInitFieldActivate(*PT, RF->Offset, E);
1255 }
1256
1257 if (!this->emitGetPtrField(RF->Offset, E))
1258 return false;
1259 if (!this->emitActivate(E))
1260 return false;
1261 return this->visitInitializerPop(SubExpr);
1262 }
1263
1264 default:
1265 return this->emitInvalid(E);
1266 }
1267 llvm_unreachable("Unhandled clang::CastKind enum");
1268}
1269
1270template <class Emitter>
1272 return this->emitBuiltinBitCast(E);
1273}
1274
1275template <class Emitter>
1277 if (DiscardResult)
1278 return true;
1279
1280 return this->emitConst(LE->getValue(), LE);
1281}
1282
1283template <class Emitter>
1285 if (DiscardResult)
1286 return true;
1287
1288 APFloat F = E->getValue();
1289 return this->emitFloat(F, E);
1290}
1291
1292template <class Emitter>
1294 assert(E->getType()->isAnyComplexType());
1295 if (DiscardResult)
1296 return true;
1297
1298 if (!Initializing) {
1299 UnsignedOrNone LocalIndex = allocateTemporary(E);
1300 if (!LocalIndex)
1301 return false;
1302 if (!this->emitGetPtrLocal(*LocalIndex, E))
1303 return false;
1304 }
1305
1306 const Expr *SubExpr = E->getSubExpr();
1307 PrimType SubExprT = classifyPrim(SubExpr->getType());
1308
1309 if (!this->visitZeroInitializer(SubExprT, SubExpr->getType(), SubExpr))
1310 return false;
1311 if (!this->emitInitElem(SubExprT, 0, SubExpr))
1312 return false;
1313 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 assert(!MD->getParent()->isInvalidDecl());
6404 return MD->getParent()->isUnion() ||
6406}
6407
6408template <class Emitter>
6410 if (E->containsErrors())
6411 return false;
6412 const FunctionDecl *FuncDecl = E->getDirectCallee();
6413
6414 if (FuncDecl) {
6415 if (unsigned BuiltinID = FuncDecl->getBuiltinID())
6416 return VisitBuiltinCallExpr(E, BuiltinID);
6417
6418 // Calls to replaceable operator new/operator delete.
6420 if (FuncDecl->getDeclName().isAnyOperatorNew())
6421 return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_new);
6422 assert(FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
6423 FuncDecl->getDeclName().getCXXOverloadedOperator() ==
6424 OO_Array_Delete);
6425 return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_delete);
6426 }
6427
6428 // Explicit calls to trivial destructors
6429 if (const auto *DD = dyn_cast<CXXDestructorDecl>(FuncDecl);
6430 DD && DD->isTrivial()) {
6431 const auto *MemberCall = cast<CXXMemberCallExpr>(E);
6432 if (!this->visit(MemberCall->getImplicitObjectArgument()))
6433 return false;
6434 return this->emitCheckDestruction(E) && this->emitEndLifetime(E) &&
6435 this->emitPopPtr(E);
6436 }
6437 }
6438
6439 // Don't generate code for method with invalid parent decls.
6440 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl);
6441 MD && MD->getParent()->isInvalidDecl())
6442 return false;
6443
6444 LocalScope<Emitter> CallScope(this, ScopeKind::Call);
6445 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
6446 bool ActivateLHS = false;
6447
6448 // Emit a special op for trivial copy/move operators.
6449 if (isTrivialMemoryOperation(dyn_cast_if_present<CXXMethodDecl>(FuncDecl))) {
6450 const Function *Func = getFunction(FuncDecl);
6451 if (!Func)
6452 return false;
6453
6454 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
6455 OCE && OCE->isAssignmentOp()) {
6456 const CXXRecordDecl *LHSRecord = Args[0]->getType()->getAsCXXRecordDecl();
6457 ActivateLHS = LHSRecord && LHSRecord->hasTrivialDefaultConstructor();
6458 }
6459 if (const auto *MCE = dyn_cast<CXXMemberCallExpr>(E))
6460 if (!this->visit(MCE->getImplicitObjectArgument()))
6461 return false;
6462
6463 if (!this->visitCallArgs(Args, FuncDecl, /*ActivateLHS=*/ActivateLHS,
6465 return false;
6466
6467 if (!this->emitTrivialCopy(ActivateLHS, Func, E))
6468 return false;
6469
6470 if (!DiscardResult)
6471 return CallScope.destroyLocals();
6472 return this->emitPopPtr(E) && CallScope.destroyLocals();
6473 }
6474
6475 QualType ReturnType = E->getCallReturnType(Ctx.getASTContext());
6477 bool HasRVO = !ReturnType->isVoidType() && !T;
6478
6479 if (HasRVO) {
6480 if (DiscardResult) {
6481 // If we need to discard the return value but the function returns its
6482 // value via an RVO pointer, we need to create one such pointer just
6483 // for this call.
6484 if (UnsignedOrNone LocalIndex = allocateLocal(E)) {
6485 if (!this->emitGetPtrLocal(*LocalIndex, E))
6486 return false;
6487 }
6488 } else {
6489 // We need the result. Prepare a pointer to return or
6490 // dup the current one.
6491 if (!Initializing) {
6492 if (UnsignedOrNone LocalIndex = allocateLocal(E)) {
6493 if (!this->emitGetPtrLocal(*LocalIndex, E))
6494 return false;
6495 }
6496 }
6497 if (!this->emitDupPtr(E))
6498 return false;
6499 }
6500 }
6501
6502 const Expr *ReversedArgs[2];
6503 bool IsAssignmentOperatorCall = false;
6504 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
6505 OCE && OCE->isAssignmentOp()) {
6506 // Just like with regular assignments, we need to special-case assignment
6507 // operators here and evaluate the RHS (the second arg) before the LHS (the
6508 // first arg). We fix this by using a Flip op later.
6509 assert(Args.size() == 2);
6510 const CXXRecordDecl *LHSRecord = Args[0]->getType()->getAsCXXRecordDecl();
6511 ActivateLHS = LHSRecord && LHSRecord->hasTrivialDefaultConstructor();
6512 IsAssignmentOperatorCall = true;
6513 ReversedArgs[0] = Args[1];
6514 ReversedArgs[1] = Args[0];
6515 Args = ReversedArgs;
6516 }
6517
6518 // Calling a static operator will still
6519 // pass the instance, but we don't need it.
6520 // Discard it here.
6521 if (isa<CXXOperatorCallExpr>(E)) {
6522 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl);
6523 MD && MD->isStatic()) {
6524 if (!this->discard(E->getArg(0)))
6525 return false;
6526 // Drop first arg.
6527 Args = Args.drop_front();
6528 }
6529 }
6530
6531 bool Devirtualized = false;
6532 UnsignedOrNone CalleeOffset = std::nullopt;
6533 // Add the (optional, implicit) This pointer.
6534 if (const auto *MC = dyn_cast<CXXMemberCallExpr>(E)) {
6535 if (!FuncDecl && classifyPrim(E->getCallee()) == PT_MemberPtr) {
6536 // If we end up creating a CallPtr op for this, we need the base of the
6537 // member pointer as the instance pointer, and later extract the function
6538 // decl as the function pointer.
6539 const Expr *Callee = E->getCallee();
6540 CalleeOffset =
6541 this->allocateLocalPrimitive(Callee, PT_MemberPtr, /*IsConst=*/true);
6542 if (!this->visit(Callee))
6543 return false;
6544 if (!this->emitSetLocal(PT_MemberPtr, *CalleeOffset, E))
6545 return false;
6546 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
6547 return false;
6548 if (!this->emitGetMemberPtrBase(E))
6549 return false;
6550 } else {
6551 const auto *InstancePtr = MC->getImplicitObjectArgument();
6552 if (isa_and_nonnull<CXXDestructorDecl>(CompilingFunction) ||
6553 isa_and_nonnull<CXXConstructorDecl>(CompilingFunction)) {
6554 const auto *Stripped = stripCheckedDerivedToBaseCasts(InstancePtr);
6555 if (isa<CXXThisExpr>(Stripped)) {
6556 FuncDecl =
6557 cast<CXXMethodDecl>(FuncDecl)->getCorrespondingMethodInClass(
6558 Stripped->getType()->getPointeeType()->getAsCXXRecordDecl());
6559 Devirtualized = true;
6560 if (!this->visit(Stripped))
6561 return false;
6562 } else {
6563 if (!this->visit(InstancePtr))
6564 return false;
6565 }
6566 } else {
6567 if (!this->visit(InstancePtr))
6568 return false;
6569 }
6570 }
6571 } else if (const auto *PD =
6572 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee())) {
6573 if (!this->emitCheckPseudoDtor(E))
6574 return false;
6575 const Expr *Base = PD->getBase();
6576 // E.g. `using T = int; 0.~T();`.
6577 if (OptPrimType BaseT = classify(Base); !BaseT || BaseT != PT_Ptr)
6578 return this->discard(Base);
6579 if (!this->visit(Base))
6580 return false;
6581 return this->emitPseudoDtor(E);
6582 } else if (!FuncDecl) {
6583 const Expr *Callee = E->getCallee();
6584 CalleeOffset =
6585 this->allocateLocalPrimitive(Callee, PT_Ptr, /*IsConst=*/true);
6586 if (!this->visit(Callee))
6587 return false;
6588 if (!this->emitSetLocal(PT_Ptr, *CalleeOffset, E))
6589 return false;
6590 }
6591
6592 if (!this->visitCallArgs(Args, FuncDecl, ActivateLHS,
6594 return false;
6595
6596 // Undo the argument reversal we did earlier.
6597 if (IsAssignmentOperatorCall) {
6598 assert(Args.size() == 2);
6599 PrimType Arg1T = classify(Args[0]).value_or(PT_Ptr);
6600 PrimType Arg2T = classify(Args[1]).value_or(PT_Ptr);
6601 if (!this->emitFlip(Arg2T, Arg1T, E))
6602 return false;
6603 }
6604
6605 if (FuncDecl) {
6606 const Function *Func = getFunction(FuncDecl);
6607 if (!Func)
6608 return false;
6609
6610 // In error cases, the function may be called with fewer arguments than
6611 // parameters.
6612 if (E->getNumArgs() < Func->getNumWrittenParams())
6613 return false;
6614
6615 assert(HasRVO == Func->hasRVO());
6616
6617 bool HasQualifier = false;
6618 if (const auto *ME = dyn_cast<MemberExpr>(E->getCallee()))
6619 HasQualifier = ME->hasQualifier();
6620
6621 bool IsVirtual = false;
6622 if (const auto *MD = dyn_cast<CXXMethodDecl>(FuncDecl))
6623 IsVirtual = !Devirtualized && MD->isVirtual();
6624
6625 // In any case call the function. The return value will end up on the stack
6626 // and if the function has RVO, we already have the pointer on the stack to
6627 // write the result into.
6628 if (IsVirtual && !HasQualifier) {
6629 uint32_t VarArgSize = 0;
6630 unsigned NumParams =
6631 Func->getNumWrittenParams() +
6632 (isa<CXXOperatorCallExpr>(E) && Func->hasImplicitThisPointer());
6633 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
6634 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6635
6636 if (!this->emitCallVirt(Func, VarArgSize, E))
6637 return false;
6638 } else if (Func->isVariadic()) {
6639 uint32_t VarArgSize = 0;
6640 unsigned NumParams =
6641 Func->getNumWrittenParams() +
6642 (isa<CXXOperatorCallExpr>(E) && Func->hasImplicitThisPointer());
6643 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
6644 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6645 if (!this->emitCallVar(Func, VarArgSize, E))
6646 return false;
6647 } else {
6648 if (!this->emitCall(Func, 0, E))
6649 return false;
6650 }
6651 } else {
6652 // Indirect call. Visit the callee, which will leave a FunctionPointer on
6653 // the stack. Cleanup of the returned value if necessary will be done after
6654 // the function call completed.
6655
6656 // Sum the size of all args from the call expr.
6657 uint32_t ArgSize = 0;
6658 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
6659 ArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6660
6661 // Get the callee, either from a member pointer or function pointer saved in
6662 // CalleeOffset.
6663 if (isa<CXXMemberCallExpr>(E) && CalleeOffset) {
6664 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
6665 return false;
6666 if (!this->emitGetMemberPtrDecl(E))
6667 return false;
6668 } else {
6669 if (!this->emitGetLocal(PT_Ptr, *CalleeOffset, E))
6670 return false;
6671 }
6672 if (!this->emitCallPtr(ArgSize, E, E))
6673 return false;
6674 }
6675
6676 // Cleanup for discarded return values.
6677 if (DiscardResult && !ReturnType->isVoidType() && T)
6678 return this->emitPop(*T, E) && CallScope.destroyLocals();
6679
6680 return CallScope.destroyLocals();
6681}
6682
6683template <class Emitter>
6685 SourceLocScope<Emitter> SLS(this, E);
6686
6687 return this->delegate(E->getExpr());
6688}
6689
6690template <class Emitter>
6692 SourceLocScope<Emitter> SLS(this, E);
6693
6694 return this->delegate(E->getExpr());
6695}
6696
6697template <class Emitter>
6699 if (DiscardResult)
6700 return true;
6701
6702 return this->emitConstBool(E->getValue(), E);
6703}
6704
6705template <class Emitter>
6707 const CXXNullPtrLiteralExpr *E) {
6708 if (DiscardResult)
6709 return true;
6710
6711 uint64_t Val = Ctx.getASTContext().getTargetNullPointerValue(E->getType());
6712 return this->emitNullPtr(Val, nullptr, E);
6713}
6714
6715template <class Emitter>
6717 if (DiscardResult)
6718 return true;
6719
6720 assert(E->getType()->isIntegerType());
6721
6723 return this->emitZero(T, E);
6724}
6725
6726template <class Emitter>
6728 if (DiscardResult)
6729 return true;
6730
6731 if constexpr (!std::is_same_v<Emitter, EvalEmitter>) {
6732 if (this->LambdaThisCapture.Offset > 0) {
6733 if (this->LambdaThisCapture.IsPtr)
6734 return this->emitGetThisFieldPtr(this->LambdaThisCapture.Offset, E);
6735 return this->emitGetPtrThisField(this->LambdaThisCapture.Offset, E);
6736 }
6737 }
6738
6739 // In some circumstances, the 'this' pointer does not actually refer to the
6740 // instance pointer of the current function frame, but e.g. to the declaration
6741 // currently being initialized. Here we emit the necessary instruction(s) for
6742 // this scenario.
6743 if (!InitStackActive || InitStack.empty())
6744 return this->emitThis(E);
6745
6746 // If our init stack is, for example:
6747 // 0 Stack: 3 (decl)
6748 // 1 Stack: 6 (init list)
6749 // 2 Stack: 1 (field)
6750 // 3 Stack: 6 (init list)
6751 // 4 Stack: 1 (field)
6752 //
6753 // We want to find the LAST element in it that's an init list,
6754 // which is marked with the K_InitList marker. The index right
6755 // before that points to an init list. We need to find the
6756 // elements before the K_InitList element that point to a base
6757 // (e.g. a decl or This), optionally followed by field, elem, etc.
6758 // In the example above, we want to emit elements [0..2].
6759 unsigned StartIndex = 0;
6760 unsigned EndIndex = 0;
6761 // Find the init list.
6762 for (StartIndex = InitStack.size() - 1; StartIndex > 0; --StartIndex) {
6763 if (InitStack[StartIndex].Kind == InitLink::K_DIE) {
6764 EndIndex = StartIndex;
6765 --StartIndex;
6766 break;
6767 }
6768 }
6769
6770 // Walk backwards to find the base.
6771 for (; StartIndex > 0; --StartIndex) {
6772 if (InitStack[StartIndex].Kind == InitLink::K_InitList)
6773 continue;
6774
6775 if (InitStack[StartIndex].Kind != InitLink::K_Field &&
6776 InitStack[StartIndex].Kind != InitLink::K_Elem &&
6777 InitStack[StartIndex].Kind != InitLink::K_Base &&
6778 InitStack[StartIndex].Kind != InitLink::K_DIE)
6779 break;
6780 }
6781
6782 if (StartIndex == 0 && EndIndex == 0)
6783 EndIndex = InitStack.size() - 1;
6784
6785 assert(InitStack[StartIndex].Kind == InitLink::K_Decl ||
6786 InitStack[StartIndex].Kind == InitLink::K_This ||
6787 InitStack[StartIndex].Kind == InitLink::K_Temp ||
6788 InitStack[StartIndex].Kind == InitLink::K_RVO);
6789
6790 // NOTE: This could be StartIndex < EndIndex, but we're also abusing the
6791 // InitStack mechanism in visitWithSubstitutions to have the This pointer
6792 // _just_ be a local variable.
6793 assert(StartIndex <= EndIndex);
6794
6795 // Emit the instructions.
6796 for (unsigned I = StartIndex; I != (EndIndex + 1); ++I) {
6797 if (InitStack[I].Kind == InitLink::K_InitList ||
6798 InitStack[I].Kind == InitLink::K_DIE)
6799 continue;
6800 if (!InitStack[I].template emit<Emitter>(this, E))
6801 return false;
6802 }
6803 return true;
6804}
6805
6806template <class Emitter> bool Compiler<Emitter>::visitStmt(const Stmt *S) {
6807 switch (S->getStmtClass()) {
6808 case Stmt::CompoundStmtClass:
6810 case Stmt::DeclStmtClass:
6811 return visitDeclStmt(cast<DeclStmt>(S), /*EvaluateConditionDecl=*/true);
6812 case Stmt::ReturnStmtClass:
6814 case Stmt::IfStmtClass:
6815 return visitIfStmt(cast<IfStmt>(S));
6816 case Stmt::WhileStmtClass:
6818 case Stmt::DoStmtClass:
6819 return visitDoStmt(cast<DoStmt>(S));
6820 case Stmt::ForStmtClass:
6821 return visitForStmt(cast<ForStmt>(S));
6822 case Stmt::CXXForRangeStmtClass:
6824 case Stmt::BreakStmtClass:
6826 case Stmt::ContinueStmtClass:
6828 case Stmt::SwitchStmtClass:
6830 case Stmt::CaseStmtClass:
6831 return visitCaseStmt(cast<CaseStmt>(S));
6832 case Stmt::DefaultStmtClass:
6834 case Stmt::AttributedStmtClass:
6836 case Stmt::CXXTryStmtClass:
6838 case Stmt::NullStmtClass:
6839 return true;
6840 // Always invalid statements.
6841 case Stmt::GCCAsmStmtClass:
6842 case Stmt::MSAsmStmtClass:
6843 case Stmt::GotoStmtClass:
6844 return this->emitInvalid(S);
6845 case Stmt::LabelStmtClass:
6846 return this->visitStmt(cast<LabelStmt>(S)->getSubStmt());
6847 case Stmt::CXXExpansionStmtInstantiationClass:
6850 default: {
6851 if (const auto *E = dyn_cast<Expr>(S))
6852 return this->discard(E);
6853 return false;
6854 }
6855 }
6856}
6857
6858template <class Emitter>
6861 for (const auto *InnerStmt : S->body())
6862 if (!visitStmt(InnerStmt))
6863 return false;
6864 return Scope.destroyLocals();
6865}
6866
6867template <class Emitter>
6868bool Compiler<Emitter>::maybeEmitDeferredVarInit(const VarDecl *VD) {
6869 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
6870 for (auto *BD : DD->flat_bindings())
6871 if (auto *KD = BD->getHoldingVar();
6872 KD && !this->visitVarDecl(KD, KD->getInit()))
6873 return false;
6874 }
6875 return true;
6876}
6877
6879 assert(FD);
6880 assert(FD->getParent()->isUnion());
6881 const CXXRecordDecl *CXXRD =
6883 return !CXXRD || CXXRD->hasTrivialDefaultConstructor();
6884}
6885
6886template <class Emitter> bool Compiler<Emitter>::refersToUnion(const Expr *E) {
6887 for (;;) {
6888 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
6889 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6890 FD && FD->getParent()->isUnion() && hasTrivialDefaultCtorParent(FD))
6891 return true;
6892 E = ME->getBase();
6893 continue;
6894 }
6895
6896 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6897 E = ASE->getBase()->IgnoreImplicit();
6898 continue;
6899 }
6900
6901 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
6902 ICE && (ICE->getCastKind() == CK_NoOp ||
6903 ICE->getCastKind() == CK_DerivedToBase ||
6904 ICE->getCastKind() == CK_UncheckedDerivedToBase)) {
6905 E = ICE->getSubExpr();
6906 continue;
6907 }
6908
6909 if (const auto *This = dyn_cast<CXXThisExpr>(E)) {
6910 const auto *ThisRecord =
6911 This->getType()->getPointeeType()->getAsRecordDecl();
6912 if (!ThisRecord->isUnion())
6913 return false;
6914 // Otherwise, always activate if we're in the ctor.
6915 if (const auto *Ctor =
6916 dyn_cast_if_present<CXXConstructorDecl>(CompilingFunction))
6917 return Ctor->getParent() == ThisRecord;
6918 return false;
6919 }
6920
6921 break;
6922 }
6923 return false;
6924}
6925
6926template <class Emitter>
6928 bool EvaluateConditionDecl) {
6929 for (const auto *D : DS->decls()) {
6932 continue;
6933
6934 if (const auto *ESD = dyn_cast<CXXExpansionStmtDecl>(D)) {
6935 assert(ESD->getInstantiations() && "not expanded?");
6936 if (!this->visitStmt(ESD->getInstantiations()))
6937 return false;
6938 continue;
6939 }
6940
6941 const auto *VD = dyn_cast<VarDecl>(D);
6942 if (!VD)
6943 return false;
6944 if (!this->visitVarDecl(VD, VD->getInit()))
6945 return false;
6946
6947 // Register decomposition decl holding vars.
6948 if (EvaluateConditionDecl && !this->maybeEmitDeferredVarInit(VD))
6949 return false;
6950 }
6951
6952 return true;
6953}
6954
6955template <class Emitter>
6957 if (this->InStmtExpr)
6958 return this->emitUnsupported(RS);
6959
6960 if (const Expr *RE = RS->getRetValue()) {
6961 LocalScope<Emitter> RetScope(this);
6962 if (ReturnType) {
6963 // Primitive types are simply returned.
6964 if (!this->visit(RE))
6965 return false;
6966 this->emitCleanup();
6967 return this->emitRet(*ReturnType, RS);
6968 }
6969
6970 if (RE->getType()->isVoidType()) {
6971 if (!this->visit(RE))
6972 return false;
6973 } else {
6974 if (RE->containsErrors())
6975 return false;
6976
6978 // RVO - construct the value in the return location.
6979 if (!this->emitRVOPtr(RE))
6980 return false;
6981 if (!this->visitInitializerPop(RE))
6982 return false;
6983
6984 this->emitCleanup();
6985 return this->emitRetVoid(RS);
6986 }
6987 }
6988
6989 // Void return.
6990 this->emitCleanup();
6991 return this->emitRetVoid(RS);
6992}
6993
6994template <class Emitter> bool Compiler<Emitter>::visitIfStmt(const IfStmt *IS) {
6995 LocalScope<Emitter> IfScope(this);
6996
6997 auto visitChildStmt = [&](const Stmt *S) -> bool {
6998 LocalScope<Emitter> SScope(this);
6999 if (!visitStmt(S))
7000 return false;
7001 return SScope.destroyLocals();
7002 };
7003
7004 if (auto *CondInit = IS->getInit()) {
7005 if (!visitStmt(CondInit))
7006 return false;
7007 }
7008
7009 if (const DeclStmt *CondDecl = IS->getConditionVariableDeclStmt()) {
7010 if (!visitDeclStmt(CondDecl))
7011 return false;
7012 }
7013
7014 // Save ourselves compiling some code and the jumps, etc. if the condition is
7015 // stataically known to be either true or false. We could look at more cases
7016 // here, but I think all the ones that actually happen are using a
7017 // ConstantExpr.
7018 if (std::optional<bool> BoolValue = getBoolValue(IS->getCond())) {
7019 if (*BoolValue)
7020 return visitChildStmt(IS->getThen());
7021 if (const Stmt *Else = IS->getElse())
7022 return visitChildStmt(Else);
7023 return true;
7024 }
7025
7026 // Otherwise, compile the condition.
7027 if (IS->isNonNegatedConsteval()) {
7028 if (!this->emitIsConstantContext(IS))
7029 return false;
7030 } else if (IS->isNegatedConsteval()) {
7031 if (!this->emitIsConstantContext(IS))
7032 return false;
7033 if (!this->emitInv(IS))
7034 return false;
7035 } else {
7037 if (!this->visitBool(IS->getCond()))
7038 return false;
7039 if (!CondScope.destroyLocals())
7040 return false;
7041 }
7042
7043 if (!this->maybeEmitDeferredVarInit(IS->getConditionVariable()))
7044 return false;
7045
7046 if (const Stmt *Else = IS->getElse()) {
7047 LabelTy LabelElse = this->getLabel();
7048 LabelTy LabelEnd = this->getLabel();
7049 if (!this->jumpFalse(LabelElse, IS))
7050 return false;
7051 if (!visitChildStmt(IS->getThen()))
7052 return false;
7053 if (!this->jump(LabelEnd, IS))
7054 return false;
7055 this->emitLabel(LabelElse);
7056 if (!visitChildStmt(Else))
7057 return false;
7058 this->emitLabel(LabelEnd);
7059 } else {
7060 LabelTy LabelEnd = this->getLabel();
7061 if (!this->jumpFalse(LabelEnd, IS))
7062 return false;
7063 if (!visitChildStmt(IS->getThen()))
7064 return false;
7065 this->emitLabel(LabelEnd);
7066 }
7067
7068 if (!IfScope.destroyLocals())
7069 return false;
7070
7071 return true;
7072}
7073
7074template <class Emitter>
7076 const Expr *Cond = S->getCond();
7077 const Stmt *Body = S->getBody();
7078
7079 LabelTy CondLabel = this->getLabel(); // Label before the condition.
7080 LabelTy EndLabel = this->getLabel(); // Label after the loop.
7081 LocalScope<Emitter> WholeLoopScope(this);
7082 LoopScope<Emitter> LS(this, S, EndLabel, CondLabel);
7083
7084 this->fallthrough(CondLabel);
7085 this->emitLabel(CondLabel);
7086
7087 // Start of the loop body {
7088 LocalScope<Emitter> CondScope(this);
7089
7090 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) {
7091 if (!visitDeclStmt(CondDecl))
7092 return false;
7093 }
7094
7095 if (!this->visitBool(Cond))
7096 return false;
7097
7098 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
7099 return false;
7100
7101 if (!this->jumpFalse(EndLabel, S))
7102 return false;
7103
7104 if (!this->visitStmt(Body))
7105 return false;
7106
7107 if (!CondScope.destroyLocals())
7108 return false;
7109 // } End of loop body.
7110
7111 if (!this->jump(CondLabel, S))
7112 return false;
7113 this->fallthrough(EndLabel);
7114 this->emitLabel(EndLabel);
7115
7116 return CondScope.destroyLocals() && WholeLoopScope.destroyLocals();
7117}
7118
7119template <class Emitter> bool Compiler<Emitter>::visitDoStmt(const DoStmt *S) {
7120 const Expr *Cond = S->getCond();
7121 const Stmt *Body = S->getBody();
7122
7123 LabelTy StartLabel = this->getLabel();
7124 LabelTy EndLabel = this->getLabel();
7125 LabelTy CondLabel = this->getLabel();
7126 LocalScope<Emitter> WholeLoopScope(this);
7127 LoopScope<Emitter> LS(this, S, EndLabel, CondLabel);
7128
7129 this->fallthrough(StartLabel);
7130 this->emitLabel(StartLabel);
7131
7132 {
7133 LocalScope<Emitter> CondScope(this);
7134 if (!this->visitStmt(Body))
7135 return false;
7136 this->fallthrough(CondLabel);
7137 this->emitLabel(CondLabel);
7138 if (!this->visitBool(Cond))
7139 return false;
7140
7141 if (!CondScope.destroyLocals())
7142 return false;
7143 }
7144 if (!this->jumpTrue(StartLabel, S))
7145 return false;
7146
7147 this->fallthrough(EndLabel);
7148 this->emitLabel(EndLabel);
7149 return WholeLoopScope.destroyLocals();
7150}
7151
7152template <class Emitter>
7154 // for (Init; Cond; Inc) { Body }
7155 const Stmt *Init = S->getInit();
7156 const Expr *Cond = S->getCond();
7157 const Expr *Inc = S->getInc();
7158 const Stmt *Body = S->getBody();
7159
7160 LabelTy EndLabel = this->getLabel();
7161 LabelTy CondLabel = this->getLabel();
7162 LabelTy IncLabel = this->getLabel();
7163
7164 LocalScope<Emitter> WholeLoopScope(this);
7165 if (Init && !this->visitStmt(Init))
7166 return false;
7167
7168 // Start of the loop body {
7169 this->fallthrough(CondLabel);
7170 this->emitLabel(CondLabel);
7171
7172 LocalScope<Emitter> CondScope(this);
7173 LoopScope<Emitter> LS(this, S, EndLabel, IncLabel);
7174 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) {
7175 if (!visitDeclStmt(CondDecl))
7176 return false;
7177 }
7178
7179 if (Cond) {
7180 if (!this->visitBool(Cond))
7181 return false;
7182 if (!this->jumpFalse(EndLabel, S))
7183 return false;
7184 }
7185 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
7186 return false;
7187
7188 if (Body && !this->visitStmt(Body))
7189 return false;
7190
7191 this->fallthrough(IncLabel);
7192 this->emitLabel(IncLabel);
7193 if (Inc && !this->discard(Inc))
7194 return false;
7195
7196 if (!CondScope.destroyLocals())
7197 return false;
7198 if (!this->jump(CondLabel, S))
7199 return false;
7200 // } End of loop body.
7201
7202 this->emitLabel(EndLabel);
7203 // If we jumped out of the loop above, we still need to clean up the condition
7204 // scope.
7205 return CondScope.destroyLocals() && WholeLoopScope.destroyLocals();
7206}
7207
7208template <class Emitter>
7210 const Stmt *Init = S->getInit();
7211 const Expr *Cond = S->getCond();
7212 const Expr *Inc = S->getInc();
7213 const Stmt *Body = S->getBody();
7214 const Stmt *BeginStmt = S->getBeginStmt();
7215 const Stmt *RangeStmt = S->getRangeStmt();
7216 const Stmt *EndStmt = S->getEndStmt();
7217
7218 LabelTy EndLabel = this->getLabel();
7219 LabelTy CondLabel = this->getLabel();
7220 LabelTy IncLabel = this->getLabel();
7221 LocalScope<Emitter> WholeLoopScope(this);
7222 LoopScope<Emitter> LS(this, S, EndLabel, IncLabel);
7223
7224 // Emit declarations needed in the loop.
7225 if (Init && !this->visitStmt(Init))
7226 return false;
7227 if (!this->visitStmt(RangeStmt))
7228 return false;
7229 if (!this->visitStmt(BeginStmt))
7230 return false;
7231 if (!this->visitStmt(EndStmt))
7232 return false;
7233
7234 LocalScope<Emitter> CondScope(this);
7235 // Now the condition as well as the loop variable assignment.
7236 this->fallthrough(CondLabel);
7237 this->emitLabel(CondLabel);
7238 if (!this->visitBool(Cond))
7239 return false;
7240 if (!this->jumpFalse(EndLabel, S))
7241 return false;
7242
7243 if (!this->visitDeclStmt(S->getLoopVarStmt(), /*EvaluateConditionDecl=*/true))
7244 return false;
7245
7246 // Body.
7247 {
7248 if (!this->visitStmt(Body))
7249 return false;
7250
7251 this->fallthrough(IncLabel);
7252 this->emitLabel(IncLabel);
7253 if (!this->discard(Inc))
7254 return false;
7255 }
7256
7257 if (!CondScope.destroyLocals())
7258 return false;
7259 if (!this->jump(CondLabel, S))
7260 return false;
7261
7262 this->fallthrough(EndLabel);
7263 this->emitLabel(EndLabel);
7264 return WholeLoopScope.destroyLocals();
7265}
7266
7267template <class Emitter>
7269 if (LabelInfoStack.empty())
7270 return this->emitInvalidTargetLabel(/*IsContinue=*/false, S);
7271
7272 OptLabelTy TargetLabel = std::nullopt;
7273 const VariableScope<Emitter> *BreakScope = nullptr;
7274
7275 if (!S->isNamed()) {
7276
7277 for (const auto &LI : llvm::reverse(LabelInfoStack)) {
7278 if (LI.BreakLabel) {
7279 TargetLabel = *LI.BreakLabel;
7280 BreakScope = LI.BreakOrContinueScope;
7281 break;
7282 }
7283 }
7284 } else {
7285 const Stmt *TargetLoop = S->getNamedLoopOrSwitch();
7286 // May be null if the named loop is outside of the
7287 // current evaluation context, i.e. not a valid target.
7288 if (!TargetLoop)
7289 return this->emitInvalidTargetLabel(/*IsContinue=*/false, S);
7290
7291 for (const auto &LI : LabelInfoStack) {
7292 if (LI.Name == TargetLoop) {
7293 TargetLabel = *LI.BreakLabel;
7294 BreakScope = LI.BreakOrContinueScope;
7295 break;
7296 }
7297 }
7298 }
7299
7300 // Faulty break statement (e.g. label redefined or named loops disabled).
7301 if (!TargetLabel)
7302 return false;
7303
7304 for (VariableScope<Emitter> *C = this->VarScope; C != BreakScope;
7305 C = C->getParent()) {
7306 if (!C->destroyLocals())
7307 return false;
7308 }
7309
7310 return this->jump(*TargetLabel, S);
7311}
7312
7313template <class Emitter>
7315 if (LabelInfoStack.empty())
7316 return this->emitInvalidTargetLabel(/*IsContinue=*/true, S);
7317
7318 OptLabelTy TargetLabel = std::nullopt;
7319 const VariableScope<Emitter> *ContinueScope = nullptr;
7320
7321 if (!S->isNamed()) {
7322 for (const auto &LI : llvm::reverse(LabelInfoStack)) {
7323 if (LI.ContinueLabel) {
7324 TargetLabel = *LI.ContinueLabel;
7325 ContinueScope = LI.BreakOrContinueScope;
7326 break;
7327 }
7328 }
7329 } else {
7330 const Stmt *TargetLoop = S->getNamedLoopOrSwitch();
7331 // May be null if the named loop is outside of the
7332 // current evaluation context, i.e. not a valid target.
7333 if (!TargetLoop)
7334 return this->emitInvalidTargetLabel(/*IsContinue=*/true, S);
7335
7336 for (auto LI : LabelInfoStack) {
7337 if (LI.Name == TargetLoop) {
7338 TargetLabel = *LI.ContinueLabel;
7339 ContinueScope = LI.BreakOrContinueScope;
7340 break;
7341 }
7342 }
7343 }
7344
7345 if (!TargetLabel)
7346 return false;
7347
7348 for (VariableScope<Emitter> *C = VarScope; C != ContinueScope;
7349 C = C->getParent()) {
7350 if (!C->destroyLocals())
7351 return false;
7352 }
7353
7354 return this->jump(*TargetLabel, S);
7355}
7356
7357template <class Emitter>
7359 const Expr *Cond = S->getCond();
7360 if (Cond->containsErrors())
7361 return false;
7362
7363 PrimType CondT = this->classifyPrim(Cond->getType());
7364 LocalScope<Emitter> LS(this);
7365 llvm::SaveAndRestore StmtExprSAR(this->SwitchInStmtExpr, this->InStmtExpr);
7366
7367 LabelTy EndLabel = this->getLabel();
7368 UnsignedOrNone DefaultLabel = std::nullopt;
7369 unsigned CondVar =
7370 this->allocateLocalPrimitive(Cond, CondT, /*IsConst=*/true);
7371
7372 if (const auto *CondInit = S->getInit())
7373 if (!visitStmt(CondInit))
7374 return false;
7375
7376 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
7377 if (!visitDeclStmt(CondDecl))
7378 return false;
7379
7380 // Initialize condition variable.
7381 if (!this->visit(Cond))
7382 return false;
7383 if (!this->emitSetLocal(CondT, CondVar, S))
7384 return false;
7385
7386 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
7387 return false;
7388
7390 // Create labels and comparison ops for all case statements.
7391 for (const SwitchCase *SC = S->getSwitchCaseList(); SC;
7392 SC = SC->getNextSwitchCase()) {
7393 if (const auto *CS = dyn_cast<CaseStmt>(SC)) {
7394 CaseLabels[SC] = this->getLabel();
7395
7396 if (CS->caseStmtIsGNURange()) {
7397 LabelTy EndOfRangeCheck = this->getLabel();
7398 const Expr *Low = CS->getLHS();
7399 const Expr *High = CS->getRHS();
7400 if (Low->isValueDependent() || High->isValueDependent())
7401 return false;
7402
7403 if (!this->emitGetLocal(CondT, CondVar, CS))
7404 return false;
7405 if (!this->visit(Low))
7406 return false;
7407 PrimType LT = this->classifyPrim(Low->getType());
7408 if (!this->emitGE(LT, S))
7409 return false;
7410 if (!this->jumpFalse(EndOfRangeCheck, S))
7411 return false;
7412
7413 if (!this->emitGetLocal(CondT, CondVar, CS))
7414 return false;
7415 if (!this->visit(High))
7416 return false;
7417 PrimType HT = this->classifyPrim(High->getType());
7418 if (!this->emitLE(HT, S))
7419 return false;
7420 if (!this->jumpTrue(CaseLabels[CS], S))
7421 return false;
7422 this->emitLabel(EndOfRangeCheck);
7423 continue;
7424 }
7425
7426 const Expr *Value = CS->getLHS();
7427 if (Value->isValueDependent())
7428 return false;
7429 PrimType ValueT = this->classifyPrim(Value->getType());
7430
7431 // Compare the case statement's value to the switch condition.
7432 if (!this->emitGetLocal(CondT, CondVar, CS))
7433 return false;
7434 if (!this->visit(Value))
7435 return false;
7436
7437 // Compare and jump to the case label.
7438 if (!this->emitEQ(ValueT, S))
7439 return false;
7440 if (!this->jumpTrue(CaseLabels[CS], S))
7441 return false;
7442 } else {
7443 assert(!DefaultLabel);
7444 DefaultLabel = this->getLabel();
7445 }
7446 }
7447
7448 // If none of the conditions above were true, fall through to the default
7449 // statement or jump after the switch statement.
7450 if (DefaultLabel) {
7451 if (!this->jump(*DefaultLabel, S))
7452 return false;
7453 } else {
7454 if (!this->jump(EndLabel, S))
7455 return false;
7456 }
7457
7458 SwitchScope<Emitter> SS(this, S, std::move(CaseLabels), EndLabel,
7459 DefaultLabel);
7460 if (!this->visitStmt(S->getBody()))
7461 return false;
7462 this->fallthrough(EndLabel);
7463 this->emitLabel(EndLabel);
7464
7465 return LS.destroyLocals();
7466}
7467
7468template <class Emitter>
7470 this->fallthrough(CaseLabels[S]);
7471 this->emitLabel(CaseLabels[S]);
7472
7473 // We can't jump from an outer switch statement to a case label
7474 // that's inside a StmtExpr.
7475 if (this->InStmtExpr && !this->SwitchInStmtExpr)
7476 return this->emitUnsupported(S);
7477
7478 return this->visitStmt(S->getSubStmt());
7479}
7480
7481template <class Emitter>
7483 if (LabelInfoStack.empty())
7484 return false;
7485
7486 LabelTy DefaultLabel;
7487 for (const LabelInfo &LI : llvm::reverse(LabelInfoStack)) {
7488 if (LI.DefaultLabel) {
7489 DefaultLabel = *LI.DefaultLabel;
7490 break;
7491 }
7492 }
7493
7494 this->emitLabel(DefaultLabel);
7495 return this->visitStmt(S->getSubStmt());
7496}
7497
7498template <class Emitter>
7500 const Stmt *SubStmt = S->getSubStmt();
7501
7502 bool IsMSVCConstexprAttr = isa<ReturnStmt>(SubStmt) &&
7504
7505 if (IsMSVCConstexprAttr && !this->emitPushMSVCCE(S))
7506 return false;
7507
7508 if (this->Ctx.getLangOpts().CXXAssumptions &&
7509 !this->Ctx.getLangOpts().MSVCCompat) {
7510 for (const Attr *A : S->getAttrs()) {
7511 auto *AA = dyn_cast<CXXAssumeAttr>(A);
7512 if (!AA)
7513 continue;
7514
7515 assert(isa<NullStmt>(SubStmt));
7516
7517 const Expr *Assumption = AA->getAssumption();
7518 if (Assumption->isValueDependent())
7519 return false;
7520
7521 if (Assumption->HasSideEffects(this->Ctx.getASTContext()))
7522 continue;
7523
7524 // Evaluate assumption.
7525 if (!this->visitBool(Assumption))
7526 return false;
7527
7528 if (!this->emitAssume(Assumption))
7529 return false;
7530 }
7531 }
7532
7533 // Ignore other attributes.
7534 if (!this->visitStmt(SubStmt))
7535 return false;
7536
7537 if (IsMSVCConstexprAttr)
7538 return this->emitPopMSVCCE(S);
7539 return true;
7540}
7541
7542template <class Emitter>
7544 // Ignore all handlers.
7545 return this->visitStmt(S->getTryBlock());
7546}
7547
7548/// template for (auto x : {1, 2}) {}
7549///
7550/// This is not a loop from an AST perspective at all since it has already
7551/// been instantiated to a list of compound statements.
7552///
7553/// Since we can have control flow in those compound statements, we need to
7554/// handle it mostly like a loop though.
7555template <class Emitter>
7558 LocalScope<Emitter> WholeLoopScope(this, ScopeKind::Block);
7559
7560 for (const Stmt *PreambleStmt : S->getPreambleStmts()) {
7561 if (!this->visitDeclStmt(cast<DeclStmt>(PreambleStmt), true))
7562 return false;
7563 }
7564
7565 LabelTy EndLabel = this->getLabel();
7566 for (const Stmt *Instantiation : S->getInstantiations()) {
7567 LabelTy ContinueLabel = this->getLabel();
7568 LoopScope<Emitter> LS(this, S, EndLabel, ContinueLabel);
7569
7570 if (!this->visitStmt(Instantiation))
7571 return false;
7572 this->emitLabel(ContinueLabel);
7573 }
7574
7575 this->emitLabel(EndLabel);
7576
7577 return WholeLoopScope.destroyLocals();
7578}
7579
7580template <class Emitter>
7581bool Compiler<Emitter>::emitLambdaStaticInvokerBody(const CXXMethodDecl *MD) {
7582 assert(MD->isLambdaStaticInvoker());
7583 assert(MD->hasBody());
7584 assert(cast<CompoundStmt>(MD->getBody())->body_empty());
7585
7586 const CXXRecordDecl *ClosureClass = MD->getParent();
7587 const FunctionDecl *LambdaCallOp;
7588 assert(ClosureClass->captures().empty());
7589 if (ClosureClass->isGenericLambda()) {
7590 LambdaCallOp = ClosureClass->getLambdaCallOperator();
7591 assert(MD->isFunctionTemplateSpecialization() &&
7592 "A generic lambda's static-invoker function must be a "
7593 "template specialization");
7595 FunctionTemplateDecl *CallOpTemplate =
7596 LambdaCallOp->getDescribedFunctionTemplate();
7597 llvm::FoldingSetInsertToken InsertToken;
7598 const FunctionDecl *CorrespondingCallOpSpecialization =
7599 CallOpTemplate->findSpecialization(TAL->asArray(), InsertToken);
7600 assert(CorrespondingCallOpSpecialization);
7601 LambdaCallOp = CorrespondingCallOpSpecialization;
7602 } else {
7603 LambdaCallOp = ClosureClass->getLambdaCallOperator();
7604 }
7605 assert(ClosureClass->captures().empty());
7606 const Function *Func = this->getFunction(LambdaCallOp);
7607 if (!Func)
7608 return false;
7609 assert(Func->hasThisPointer());
7610 assert(Func->getNumParams() == (MD->getNumParams() + 1 + Func->hasRVO()));
7611
7612 if (Func->hasRVO()) {
7613 if (!this->emitRVOPtr(MD))
7614 return false;
7615 }
7616
7617 // The lambda call operator needs an instance pointer, but we don't have
7618 // one here, and we don't need one either because the lambda cannot have
7619 // any captures, as verified above. Emit a null pointer. This is then
7620 // special-cased when interpreting to not emit any misleading diagnostics.
7621 if (!this->emitNullPtr(0, nullptr, MD))
7622 return false;
7623
7624 // Forward all arguments from the static invoker to the lambda call operator.
7625 for (const ParmVarDecl *PVD : MD->parameters()) {
7626 auto It = this->Params.find(PVD);
7627 assert(It != this->Params.end());
7628
7629 // We do the lvalue-to-rvalue conversion manually here, so no need
7630 // to care about references.
7631 PrimType ParamType = this->classify(PVD->getType()).value_or(PT_Ptr);
7632 if (!this->emitGetParam(ParamType, It->second.Index, MD))
7633 return false;
7634 }
7635
7636 if (!this->emitCall(Func, 0, LambdaCallOp))
7637 return false;
7638
7639 this->emitCleanup();
7640 if (ReturnType)
7641 return this->emitRet(*ReturnType, MD);
7642
7643 // Nothing to do, since we emitted the RVO pointer above.
7644 return this->emitRetVoid(MD);
7645}
7646
7647template <class Emitter>
7648bool Compiler<Emitter>::checkLiteralType(const Expr *E) {
7649 if (Ctx.getLangOpts().CPlusPlus23)
7650 return true;
7651
7652 if (!E->isPRValue() || E->getType()->isLiteralType(Ctx.getASTContext()))
7653 return true;
7654
7655 return this->emitCheckLiteralType(E->getType().getTypePtr(), E);
7656}
7657
7659 const Expr *InitExpr = Init->getInit();
7660
7661 if (!Init->isWritten() && !Init->isInClassMemberInitializer() &&
7662 !isa<CXXConstructExpr>(InitExpr))
7663 return true;
7664
7665 if (const auto *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
7666 const CXXConstructorDecl *Ctor = CE->getConstructor();
7667 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
7668 Ctor->isTrivial())
7669 return true;
7670 }
7671
7672 return false;
7673}
7674
7675template <class Emitter>
7676bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
7677 assert(!ReturnType);
7678
7679 // Only start the lifetime of the instance pointer.
7680 if (!this->emitStartThisLifetime1(Ctor))
7681 return false;
7682
7683 auto emitFieldInitializer = [&](const Record::Field *F, unsigned FieldOffset,
7684 const Expr *InitExpr,
7685 bool Activate = false) -> bool {
7686 // We don't know what to do with these, so just return false.
7687 if (InitExpr->getType().isNull())
7688 return false;
7689
7690 if (OptPrimType T = this->classify(InitExpr)) {
7691 if (Activate && !this->emitActivateThisField(FieldOffset, InitExpr))
7692 return false;
7693
7694 if (!this->visit(InitExpr))
7695 return false;
7696
7697 if (F->isBitField())
7698 return this->emitInitThisBitField(*T, FieldOffset, F->bitWidth(),
7699 InitExpr);
7700 return this->emitInitThisField(*T, FieldOffset, InitExpr);
7701 }
7702 // Non-primitive case. Get a pointer to the field-to-initialize
7703 // on the stack and call visitInitialzer() for it.
7704 InitLinkScope<Emitter> FieldScope(this, InitLink::Field(F->Offset));
7705 if (!this->emitGetPtrThisField(FieldOffset, InitExpr))
7706 return false;
7707
7708 if (Activate && !this->emitActivate(InitExpr))
7709 return false;
7710
7711 return this->visitInitializerPop(InitExpr);
7712 };
7713
7714 const RecordDecl *RD = Ctor->getParent();
7715 const Record *R = this->getRecord(RD);
7716 if (!R)
7717 return false;
7718 bool IsUnion = R->isUnion();
7719
7720 // Default union copy and move ctors are special.
7721 if (IsUnion && Ctor->isCopyOrMoveConstructor() && Ctor->isDefaulted()) {
7723
7724 // No special case for NumFields == 0 here, so the Memcpy op
7725 // below also does its checks in those cases.
7726
7727 assert(cast<CompoundStmt>(Ctor->getBody())->body_empty());
7728 if (!this->emitThis(Ctor))
7729 return false;
7730
7731 if (!this->emitGetParam(PT_Ptr, /*ParamIndex=*/0, Ctor))
7732 return false;
7733
7734 return this->emitMemcpy(Ctor) && this->emitPopPtr(Ctor) &&
7735 this->emitRetVoid(Ctor);
7736 }
7737
7738 unsigned FieldInits = 0;
7739 InitLinkScope<Emitter> InitScope(this, InitLink::This());
7740 // First, initialize virtual bases if the records has them.
7741 if (R->getNumVirtualBases() > 0) {
7742 if (!this->emitThis(Ctor))
7743 return false;
7744 LabelTy AfterVirtBasesLabel = this->getLabel();
7745
7746 // If the instance pointer is a base class, skip the virtual bases.
7747 if (!this->emitIsBaseClass({}))
7748 return false;
7749 if (!this->jumpTrue(AfterVirtBasesLabel, {}))
7750 return false;
7751
7752 for (const auto *Init : Ctor->inits()) {
7753 if (const Type *Base = Init->getBaseClass();
7754 Base && Init->isBaseVirtual()) {
7755 const auto *BaseDecl = Base->getAsCXXRecordDecl();
7756 assert(BaseDecl);
7757 assert(R->findVirtualBase(BaseDecl));
7758 if (!this->emitGetPtrThisVirtBase(BaseDecl, Ctor))
7759 return false;
7760 if (!this->visitInitializerPop(Init->getInit()))
7761 return false;
7762 }
7763 }
7764
7765 this->fallthrough(AfterVirtBasesLabel);
7766 this->emitLabel(AfterVirtBasesLabel);
7767
7768 if (!this->emitPopPtr(Ctor))
7769 return false;
7770 }
7771
7772 for (const auto *Init : Ctor->inits()) {
7773 // Scope needed for the initializers.
7774 LocalScope<Emitter> Scope(this, ScopeKind::FullExpression);
7775
7776 const Expr *InitExpr = Init->getInit();
7777 if (const FieldDecl *Member = Init->getMember()) {
7778 const Record::Field *F = R->getField(Member);
7779
7782 if (!emitFieldInitializer(F, F->Offset, InitExpr, IsUnion))
7783 return false;
7784 ++FieldInits;
7785 } else if (const Type *Base = Init->getBaseClass()) {
7786 const auto *BaseDecl = Base->getAsCXXRecordDecl();
7787 assert(BaseDecl);
7788
7789 if (Init->isBaseVirtual()) {
7790 // See above.
7791 continue;
7792 } else {
7793 // Base class initializer.
7794 // Get This Base and call initializer on it.
7795 const Record::Base *B = R->getBase(BaseDecl);
7796 assert(B);
7797 if (!this->emitGetPtrThisBase(B->Offset, InitExpr))
7798 return false;
7799 }
7800
7801 if (!this->visitInitializerPop(InitExpr))
7802 return false;
7803 } else if (const IndirectFieldDecl *IFD = Init->getIndirectMember()) {
7806 unsigned ChainSize = IFD->getChainingSize();
7807 assert(ChainSize >= 2);
7808
7809 unsigned NestedFieldOffset = 0;
7810 const Record::Field *NestedField = nullptr;
7811 for (unsigned I = 0; I != ChainSize; ++I) {
7812 const auto *FD = cast<FieldDecl>(IFD->chain()[I]);
7813 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
7814 assert(FieldRecord);
7815
7816 NestedField = FieldRecord->getField(FD);
7817 assert(NestedField);
7818 IsUnion = IsUnion || FieldRecord->isUnion();
7819
7820 NestedFieldOffset += NestedField->Offset;
7821
7822 // Add a new InitChainLink for the record, but not for the final field.
7823 if (I != ChainSize - 1)
7824 InitStack.push_back(InitLink::Field(NestedField->Offset));
7825 }
7826 assert(NestedField);
7827
7829 if (!emitFieldInitializer(NestedField, NestedFieldOffset, InitExpr,
7830 IsUnion))
7831 return false;
7832
7833 // Mark all chain links as initialized.
7834 unsigned InitFieldOffset = 0;
7835 for (const NamedDecl *ND : IFD->chain().drop_back()) {
7836 const auto *FD = cast<FieldDecl>(ND);
7837 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
7838 assert(FieldRecord);
7839 NestedField = FieldRecord->getField(FD);
7840 InitFieldOffset += NestedField->Offset;
7841 assert(NestedField);
7842 if (!this->emitGetPtrThisField(InitFieldOffset, InitExpr))
7843 return false;
7844 if (!this->emitFinishInitPop(InitExpr))
7845 return false;
7846 }
7847
7848 InitStack.pop_back_n(ChainSize - 1);
7849
7850 } else {
7851 assert(Init->isDelegatingInitializer());
7852 if (!this->emitThis(InitExpr))
7853 return false;
7854 if (!this->visitInitializerPop(Init->getInit()))
7855 return false;
7856 }
7857
7858 if (!Scope.destroyLocals())
7859 return false;
7860 }
7861
7862 if (FieldInits != R->getNumFields()) {
7863 assert(FieldInits < R->getNumFields());
7864 // Start the lifetime of all members.
7865 if (!this->emitStartThisLifetime(Ctor))
7866 return false;
7867 }
7868
7869 if (const Stmt *Body = Ctor->getBody()) {
7870 // Only emit the CtorCheck op for non-empty CompoundStmt bodies.
7871 // For non-CompoundStmts, always assume they are non-empty and emit it.
7872 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
7873 if (!CS->body_empty() && !this->emitCtorCheck(SourceInfo{}))
7874 return false;
7875 } else {
7876 if (!this->emitCtorCheck(SourceInfo{}))
7877 return false;
7878 }
7879
7880 if (!visitStmt(Body))
7881 return false;
7882 }
7883
7884 return this->emitRetVoid(SourceInfo{});
7885}
7886
7887template <class Emitter>
7888bool Compiler<Emitter>::compileDestructor(const CXXDestructorDecl *Dtor) {
7889 const RecordDecl *RD = Dtor->getParent();
7890 const Record *R = this->getRecord(RD);
7891 if (!R)
7892 return false;
7893
7894 if (!Dtor->isTrivial() && Dtor->getBody()) {
7895 if (!this->visitStmt(Dtor->getBody()))
7896 return false;
7897 }
7898
7899 if (!this->emitThis(Dtor))
7900 return false;
7901
7902 if (!this->emitCheckDestruction(Dtor))
7903 return false;
7904
7905 assert(R);
7906 if (!R->isUnion()) {
7907
7909 // First, destroy all fields.
7910 for (const Record::Field &Field : llvm::reverse(R->fields())) {
7911 const Descriptor *D = Field.Desc;
7912 if (D->hasTrivialDtor())
7913 continue;
7914 if (!this->emitGetPtrField(Field.Offset, SourceInfo{}))
7915 return false;
7916 if (!this->emitDestructionPop(D, SourceInfo{}))
7917 return false;
7918 }
7919 }
7920
7921 for (const Record::Base &Base : llvm::reverse(R->bases())) {
7922 if (Base.R->hasTrivialDtor())
7923 continue;
7924 if (!this->emitGetPtrBase(Base.Offset, SourceInfo{}))
7925 return false;
7926 if (!this->emitRecordDestructionPop(Base.R, {}))
7927 return false;
7928 }
7929
7930 if (R->getNumVirtualBases() > 0) {
7931 LabelTy EndLabel = this->getLabel();
7932 // If this is a base class, skip the virtual bases.
7933 if (!this->emitIsBaseClass({}))
7934 return false;
7935 if (!this->jumpTrue(EndLabel, {}))
7936 return false;
7937
7938 for (const Record::Base &Base : llvm::reverse(R->virtual_bases())) {
7939 if (Base.R->hasTrivialDtor())
7940 continue;
7941 if (!this->emitGetPtrVirtBase(cast<CXXRecordDecl>(Base.R->getDecl()),
7942 SourceInfo{}))
7943 return false;
7944 if (!this->emitRecordDestructionPop(Base.R, {}))
7945 return false;
7946 }
7947
7948 this->fallthrough(EndLabel);
7949 this->emitLabel(EndLabel);
7950 }
7951
7952 if (!this->emitMarkDestroyed(Dtor))
7953 return false;
7954
7955 return this->emitPopPtr(Dtor) && this->emitRetVoid(Dtor);
7956}
7957
7958template <class Emitter>
7959bool Compiler<Emitter>::compileUnionAssignmentOperator(
7960 const CXXMethodDecl *MD) {
7961 if (!this->emitThis(MD))
7962 return false;
7963
7964 if (!this->emitGetParam(PT_Ptr, /*ParamIndex=*/0, MD))
7965 return false;
7966
7967 return this->emitMemcpy(MD) && this->emitRet(PT_Ptr, MD);
7968}
7969
7970template <class Emitter>
7972 if (F->getReturnType()->isDependentType())
7973 return false;
7974
7975 // Classify the return type.
7976 ReturnType = this->classify(F->getReturnType());
7977
7978 this->CompilingFunction = F;
7979
7980 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(F))
7981 return this->compileConstructor(Ctor);
7982 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(F))
7983 return this->compileDestructor(Dtor);
7984
7985 // Emit custom code if this is a lambda static invoker.
7986 if (const auto *MD = dyn_cast<CXXMethodDecl>(F)) {
7987 const RecordDecl *RD = MD->getParent();
7988
7989 if (RD->isUnion() &&
7991 return this->compileUnionAssignmentOperator(MD);
7992
7993 if (MD->isLambdaStaticInvoker())
7994 return this->emitLambdaStaticInvokerBody(MD);
7995 }
7996
7997 // Regular functions.
7998 if (const auto *Body = F->getBody())
7999 if (!visitStmt(Body))
8000 return false;
8001
8002 // Emit a guard return to protect against a code path missing one.
8003 if (F->getReturnType()->isVoidType())
8004 return this->emitRetVoid(SourceInfo{});
8005 return this->emitNoRet(SourceInfo{});
8006}
8007
8008static uint32_t getBitWidth(const Expr *E) {
8009 assert(E->refersToBitField());
8010 const auto *ME = cast<MemberExpr>(E);
8011 const auto *FD = cast<FieldDecl>(ME->getMemberDecl());
8012 return FD->getBitWidthValue();
8013}
8014
8015template <class Emitter>
8017 if (E->containsErrors())
8018 return false;
8019
8020 const Expr *SubExpr = E->getSubExpr();
8021 if (SubExpr->getType()->isAnyComplexType())
8022 return this->VisitComplexUnaryOperator(E);
8023 if (SubExpr->getType()->isVectorType())
8024 return this->VisitVectorUnaryOperator(E);
8025 if (SubExpr->getType()->isFixedPointType())
8026 return this->VisitFixedPointUnaryOperator(E);
8027 OptPrimType T = classify(SubExpr->getType());
8028
8029 switch (E->getOpcode()) {
8030 case UO_PostInc: { // x++
8031 if (!Ctx.getLangOpts().CPlusPlus14)
8032 return this->emitInvalid(E);
8033 if (!T)
8034 return this->emitError(E);
8035
8036 if (!this->visit(SubExpr))
8037 return false;
8038
8039 if (T == PT_Ptr) {
8040 if (!this->emitIncPtr(E))
8041 return false;
8042
8043 return DiscardResult ? this->emitPopPtr(E) : true;
8044 }
8045
8046 if (T == PT_Float)
8047 return DiscardResult ? this->emitIncfPop(getFPOptions(E), E)
8048 : this->emitIncf(getFPOptions(E), E);
8049
8050 if (SubExpr->refersToBitField())
8051 return DiscardResult ? this->emitIncPopBitfield(*T, E->canOverflow(),
8052 getBitWidth(SubExpr), E)
8053 : this->emitIncBitfield(*T, E->canOverflow(),
8054 getBitWidth(SubExpr), E);
8055
8056 return DiscardResult ? this->emitIncPop(*T, E->canOverflow(), E)
8057 : this->emitInc(*T, E->canOverflow(), E);
8058 }
8059 case UO_PostDec: { // x--
8060 if (!Ctx.getLangOpts().CPlusPlus14)
8061 return this->emitInvalid(E);
8062 if (!T)
8063 return this->emitError(E);
8064
8065 if (!this->visit(SubExpr))
8066 return false;
8067
8068 if (T == PT_Ptr) {
8069 if (!this->emitDecPtr(E))
8070 return false;
8071
8072 return DiscardResult ? this->emitPopPtr(E) : true;
8073 }
8074
8075 if (T == PT_Float)
8076 return DiscardResult ? this->emitDecfPop(getFPOptions(E), E)
8077 : this->emitDecf(getFPOptions(E), E);
8078
8079 if (SubExpr->refersToBitField()) {
8080 return DiscardResult ? this->emitDecPopBitfield(*T, E->canOverflow(),
8081 getBitWidth(SubExpr), E)
8082 : this->emitDecBitfield(*T, E->canOverflow(),
8083 getBitWidth(SubExpr), E);
8084 }
8085
8086 return DiscardResult ? this->emitDecPop(*T, E->canOverflow(), E)
8087 : this->emitDec(*T, E->canOverflow(), E);
8088 }
8089 case UO_PreInc: { // ++x
8090 if (!Ctx.getLangOpts().CPlusPlus14)
8091 return this->emitInvalid(E);
8092 if (!T)
8093 return this->emitError(E);
8094
8095 if (!this->visit(SubExpr))
8096 return false;
8097
8098 if (T == PT_Ptr) {
8099 if (!this->emitLoadPtr(E))
8100 return false;
8101 if (!this->emitConstUint8(1, E))
8102 return false;
8103 if (!this->emitAddOffsetUint8(E))
8104 return false;
8105 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
8106 }
8107
8108 // Post-inc and pre-inc are the same if the value is to be discarded.
8109 if (DiscardResult) {
8110 if (T == PT_Float)
8111 return this->emitIncfPop(getFPOptions(E), E);
8112 if (SubExpr->refersToBitField())
8113 return DiscardResult ? this->emitIncPopBitfield(*T, E->canOverflow(),
8114 getBitWidth(SubExpr), E)
8115 : this->emitIncBitfield(*T, E->canOverflow(),
8116 getBitWidth(SubExpr), E);
8117 return this->emitIncPop(*T, E->canOverflow(), E);
8118 }
8119
8120 if (T == PT_Float) {
8121 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
8122 if (!this->emitLoadFloat(E))
8123 return false;
8124 APFloat F(TargetSemantics, 1);
8125 if (!this->emitFloat(F, E))
8126 return false;
8127
8128 if (!this->emitAddf(getFPOptions(E), E))
8129 return false;
8130 if (!this->emitStoreFloat(E))
8131 return false;
8132 } else if (SubExpr->refersToBitField()) {
8133 assert(isIntegerOrBoolType(*T));
8134 if (!this->emitPreIncBitfield(*T, E->canOverflow(), getBitWidth(SubExpr),
8135 E))
8136 return false;
8137 } else {
8138 assert(isIntegerOrBoolType(*T));
8139 if (!this->emitPreInc(*T, E->canOverflow(), E))
8140 return false;
8141 }
8142 return E->isGLValue() || this->emitLoadPop(*T, E);
8143 }
8144 case UO_PreDec: { // --x
8145 if (!Ctx.getLangOpts().CPlusPlus14)
8146 return this->emitInvalid(E);
8147 if (!T)
8148 return this->emitError(E);
8149
8150 if (!this->visit(SubExpr))
8151 return false;
8152
8153 if (T == PT_Ptr) {
8154 if (!this->emitLoadPtr(E))
8155 return false;
8156 if (!this->emitConstUint8(1, E))
8157 return false;
8158 if (!this->emitSubOffsetUint8(E))
8159 return false;
8160 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
8161 }
8162
8163 // Post-dec and pre-dec are the same if the value is to be discarded.
8164 if (DiscardResult) {
8165 if (T == PT_Float)
8166 return this->emitDecfPop(getFPOptions(E), E);
8167 if (SubExpr->refersToBitField())
8168 return DiscardResult ? this->emitDecPopBitfield(*T, E->canOverflow(),
8169 getBitWidth(SubExpr), E)
8170 : this->emitDecBitfield(*T, E->canOverflow(),
8171 getBitWidth(SubExpr), E);
8172 return this->emitDecPop(*T, E->canOverflow(), E);
8173 }
8174
8175 if (T == PT_Float) {
8176 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
8177 if (!this->emitLoadFloat(E))
8178 return false;
8179 APFloat F(TargetSemantics, 1);
8180 if (!this->emitFloat(F, E))
8181 return false;
8182
8183 if (!this->emitSubf(getFPOptions(E), E))
8184 return false;
8185 if (!this->emitStoreFloat(E))
8186 return false;
8187 } else if (SubExpr->refersToBitField()) {
8188 assert(isIntegerOrBoolType(*T));
8189 if (!this->emitPreDecBitfield(*T, E->canOverflow(), getBitWidth(SubExpr),
8190 E))
8191 return false;
8192 } else {
8193 assert(isIntegerOrBoolType(*T));
8194 if (!this->emitPreDec(*T, E->canOverflow(), E))
8195 return false;
8196 }
8197 return E->isGLValue() || this->emitLoadPop(*T, E);
8198 }
8199 case UO_LNot: // !x
8200 if (!T)
8201 return this->emitError(E);
8202
8203 if (DiscardResult)
8204 return this->discard(SubExpr);
8205
8206 if (!this->visitBool(SubExpr))
8207 return false;
8208
8209 if (!this->emitInv(E))
8210 return false;
8211
8212 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
8213 return this->emitCast(PT_Bool, ET, E);
8214 return true;
8215 case UO_Minus: // -x
8216 if (!T)
8217 return this->emitError(E);
8218
8219 if (!this->visit(SubExpr))
8220 return false;
8221 return DiscardResult ? this->emitPop(*T, E) : this->emitNeg(*T, E);
8222 case UO_Plus: // +x
8223 if (!T)
8224 return this->emitError(E);
8225
8226 if (!this->visit(SubExpr)) // noop
8227 return false;
8228 return DiscardResult ? this->emitPop(*T, E) : true;
8229 case UO_AddrOf: // &x
8230 if (E->getType()->isMemberPointerType()) {
8231 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
8232 // member can be formed.
8233 if (DiscardResult)
8234 return true;
8235 return this->emitGetMemberPtr(cast<DeclRefExpr>(SubExpr)->getDecl(), E);
8236 }
8237 // [C11 6.5.3.2p3]: if the operand of '&' is the result of a unary '*'
8238 // operator, neither operator is evaluated and the result is as if both
8239 // were omitted. So '&*q' is just 'q' with no dereference; delegate to the
8240 // pointer operand directly instead of to the '*' (which would emit a null
8241 // check), so that e.g. '&*(int *)0' is not rejected.
8242 if (!Ctx.getLangOpts().CPlusPlus) {
8243 const Expr *Sub = SubExpr->IgnoreParens();
8244
8245 if (const auto *Deref = dyn_cast<UnaryOperator>(Sub);
8246 Deref && Deref->getOpcode() == UO_Deref) {
8247 if (DiscardResult)
8248 return this->discard(Deref->getSubExpr());
8249 return this->visit(Deref->getSubExpr()) && this->emitAddrOf(E);
8250 }
8251 }
8252 // We should already have a pointer when we get here.
8253 if (DiscardResult)
8254 return this->discard(SubExpr);
8255 return this->delegate(SubExpr) && this->emitAddrOf(E);
8256 case UO_Deref: // *x
8257 if (DiscardResult)
8258 return this->discard(SubExpr);
8259
8260 if (!this->visit(SubExpr))
8261 return false;
8262
8263 if (!SubExpr->getType()->isFunctionPointerType() && !this->emitCheckNull(E))
8264 return false;
8265
8266 if (classifyPrim(SubExpr) == PT_Ptr)
8267 return this->emitNarrowPtr(E);
8268 return true;
8269
8270 case UO_Not: // ~x
8271 if (!T)
8272 return this->emitError(E);
8273
8274 if (!this->visit(SubExpr))
8275 return false;
8276 return DiscardResult ? this->emitPop(*T, E) : this->emitComp(*T, E);
8277 case UO_Real: // __real x
8278 if (!T)
8279 return false;
8280 return this->delegate(SubExpr);
8281 case UO_Imag: { // __imag x
8282 if (!T)
8283 return false;
8284 if (!this->discard(SubExpr))
8285 return false;
8286 return DiscardResult
8287 ? true
8288 : this->visitZeroInitializer(*T, SubExpr->getType(), SubExpr);
8289 }
8290 case UO_Extension:
8291 return this->delegate(SubExpr);
8292 case UO_Coawait:
8293 assert(false && "Unhandled opcode");
8294 }
8295
8296 return false;
8297}
8298
8299template <class Emitter>
8301 const Expr *SubExpr = E->getSubExpr();
8302 assert(SubExpr->getType()->isAnyComplexType());
8303
8304 if (DiscardResult)
8305 return this->discard(SubExpr);
8306
8307 OptPrimType ResT = classify(E);
8308 auto prepareResult = [=]() -> bool {
8309 if (!ResT && !Initializing) {
8310 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
8311 if (!LocalIndex)
8312 return false;
8313 return this->emitGetPtrLocal(*LocalIndex, E);
8314 }
8315
8316 return true;
8317 };
8318
8319 // The offset of the temporary, if we created one.
8320 unsigned SubExprOffset = ~0u;
8321 auto createTemp = [=, &SubExprOffset]() -> bool {
8322 SubExprOffset =
8323 this->allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
8324 if (!this->visit(SubExpr))
8325 return false;
8326 return this->emitSetLocal(PT_Ptr, SubExprOffset, E);
8327 };
8328
8329 PrimType ElemT = classifyComplexElementType(SubExpr->getType());
8330 auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
8331 if (!this->emitGetLocal(PT_Ptr, Offset, E))
8332 return false;
8333 return this->emitArrayElemPop(ElemT, Index, E);
8334 };
8335
8336 switch (E->getOpcode()) {
8337 case UO_Minus: // -x
8338 if (!prepareResult())
8339 return false;
8340 if (!createTemp())
8341 return false;
8342 for (unsigned I = 0; I != 2; ++I) {
8343 if (!getElem(SubExprOffset, I))
8344 return false;
8345 if (!this->emitNeg(ElemT, E))
8346 return false;
8347 if (!this->emitInitElem(ElemT, I, E))
8348 return false;
8349 }
8350 break;
8351
8352 case UO_Plus: // +x
8353 case UO_AddrOf: // &x
8354 case UO_Deref: // *x
8355 return this->delegate(SubExpr);
8356
8357 case UO_LNot:
8358 if (!this->visit(SubExpr))
8359 return false;
8360 if (!this->emitComplexBoolCast(SubExpr))
8361 return false;
8362 if (!this->emitInv(E))
8363 return false;
8364 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
8365 return this->emitCast(PT_Bool, ET, E);
8366 return true;
8367
8368 case UO_Real:
8369 return this->emitComplexReal(SubExpr);
8370
8371 case UO_Imag:
8372 if (!this->visit(SubExpr))
8373 return false;
8374
8375 if (SubExpr->isLValue()) {
8376 if (!this->emitConstUint8(1, E))
8377 return false;
8378 return this->emitArrayElemPtrPopUint8(E);
8379 }
8380
8381 // Since our _Complex implementation does not map to a primitive type,
8382 // we sometimes have to do the lvalue-to-rvalue conversion here manually.
8383 return this->emitArrayElemPop(classifyPrim(E->getType()), 1, E);
8384
8385 case UO_Not: // ~x
8386 if (!this->delegate(SubExpr))
8387 return false;
8388 // Negate the imaginary component.
8389 if (!this->emitArrayElem(ElemT, 1, E))
8390 return false;
8391 if (!this->emitNeg(ElemT, E))
8392 return false;
8393 if (!this->emitInitElem(ElemT, 1, E))
8394 return false;
8395 return DiscardResult ? this->emitPopPtr(E) : true;
8396
8397 case UO_Extension:
8398 return this->delegate(SubExpr);
8399
8400 default:
8401 return this->emitInvalid(E);
8402 }
8403
8404 return true;
8405}
8406
8407template <class Emitter>
8409 const Expr *SubExpr = E->getSubExpr();
8410 assert(SubExpr->getType()->isVectorType());
8411
8412 if (DiscardResult)
8413 return this->discard(SubExpr);
8414
8415 auto UnaryOp = E->getOpcode();
8416 if (UnaryOp == UO_Extension)
8417 return this->delegate(SubExpr);
8418
8419 if (UnaryOp != UO_Plus && UnaryOp != UO_Minus && UnaryOp != UO_LNot &&
8420 UnaryOp != UO_Not && UnaryOp != UO_AddrOf)
8421 return this->emitInvalid(E);
8422
8423 // Nothing to do here.
8424 if (UnaryOp == UO_Plus || UnaryOp == UO_AddrOf)
8425 return this->delegate(SubExpr);
8426
8427 if (!Initializing) {
8428 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
8429 if (!LocalIndex)
8430 return false;
8431 if (!this->emitGetPtrLocal(*LocalIndex, E))
8432 return false;
8433 }
8434
8435 // The offset of the temporary, if we created one.
8436 unsigned SubExprOffset =
8437 this->allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
8438 if (!this->visit(SubExpr))
8439 return false;
8440 if (!this->emitSetLocal(PT_Ptr, SubExprOffset, E))
8441 return false;
8442
8443 const auto *VecTy = SubExpr->getType()->getAs<VectorType>();
8444 PrimType ElemT = classifyVectorElementType(SubExpr->getType());
8445 auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
8446 if (!this->emitGetLocal(PT_Ptr, Offset, E))
8447 return false;
8448 return this->emitArrayElemPop(ElemT, Index, E);
8449 };
8450
8451 switch (UnaryOp) {
8452 case UO_Minus:
8453 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8454 if (!getElem(SubExprOffset, I))
8455 return false;
8456 if (!this->emitNeg(ElemT, E))
8457 return false;
8458 if (!this->emitInitElem(ElemT, I, E))
8459 return false;
8460 }
8461 break;
8462 case UO_LNot: { // !x
8463 // In C++, the logic operators !, &&, || are available for vectors. !v is
8464 // equivalent to v == 0.
8465 //
8466 // The result of the comparison is a vector of the same width and number of
8467 // elements as the comparison operands with a signed integral element type.
8468 //
8469 // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html
8470 QualType ResultVecTy = E->getType();
8471 PrimType ResultVecElemT =
8472 classifyPrim(ResultVecTy->getAs<VectorType>()->getElementType());
8473 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8474 if (!getElem(SubExprOffset, I))
8475 return false;
8476 // operator ! on vectors returns -1 for 'truth', so negate it.
8477 if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
8478 return false;
8479 if (!this->emitInv(E))
8480 return false;
8481 if (!this->emitPrimCast(PT_Bool, ElemT, VecTy->getElementType(), E))
8482 return false;
8483 if (!this->emitNeg(ElemT, E))
8484 return false;
8485 if (ElemT != ResultVecElemT &&
8486 !this->emitPrimCast(ElemT, ResultVecElemT, ResultVecTy, E))
8487 return false;
8488 if (!this->emitInitElem(ResultVecElemT, I, E))
8489 return false;
8490 }
8491 break;
8492 }
8493 case UO_Not: // ~x
8494 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8495 if (!getElem(SubExprOffset, I))
8496 return false;
8497 if (ElemT == PT_Bool) {
8498 if (!this->emitInv(E))
8499 return false;
8500 } else {
8501 if (!this->emitComp(ElemT, E))
8502 return false;
8503 }
8504 if (!this->emitInitElem(ElemT, I, E))
8505 return false;
8506 }
8507 break;
8508 default:
8509 llvm_unreachable("Unsupported unary operators should be handled up front");
8510 }
8511 return true;
8512}
8513
8514template <class Emitter>
8516 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
8517 if (DiscardResult)
8518 return true;
8519 return this->emitConst(ECD->getInitVal(), E);
8520 }
8521 if (const auto *FuncDecl = dyn_cast<FunctionDecl>(D)) {
8522 if (DiscardResult)
8523 return true;
8524 const Function *F = getFunction(FuncDecl);
8525 return F && this->emitGetFnPtr(F, E);
8526 }
8527 if (const auto *TPOD = dyn_cast<TemplateParamObjectDecl>(D)) {
8528 TPOD = TPOD->getFirstDecl();
8529 if (DiscardResult)
8530 return true;
8531 if (UnsignedOrNone GlobalIndex = P.getGlobal(TPOD))
8532 return this->emitGetPtrGlobal(*GlobalIndex, E);
8533
8534 if (UnsignedOrNone Index = P.getOrCreateGlobal(TPOD)) {
8535 if (OptPrimType T = classify(TPOD->getType())) {
8536 if (!this->visitAPValue(TPOD->getValue(), *T, E))
8537 return false;
8538 return this->emitInitGlobal(*T, *Index, E);
8539 }
8540
8541 if (!this->emitGetPtrGlobal(*Index, E))
8542 return false;
8543 if (!this->visitAPValueInitializer(TPOD->getValue(), E, TPOD->getType()))
8544 return false;
8545 return this->emitFinishInit(E);
8546 }
8547 return false;
8548 }
8549
8550 // References are implemented via pointers, so when we see a DeclRefExpr
8551 // pointing to a reference, we need to get its value directly (i.e. the
8552 // pointer to the actual value) instead of a pointer to the pointer to the
8553 // value.
8554 QualType DeclType = D->getType();
8555 bool IsReference = DeclType->isReferenceType();
8556
8557 auto maybePopPtr = [&]() -> bool {
8558 if (DiscardResult)
8559 return this->emitPopPtr(E);
8560 return true;
8561 };
8562
8563 // Function parameters.
8564 // Note that it's important to check them first since we might have a local
8565 // variable created for a ParmVarDecl as well.
8566 if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
8567 if (DiscardResult)
8568 return true;
8569
8570 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
8571 !DeclType->isIntegralOrEnumerationType()) {
8572 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8573 /*InitializerFailed=*/false, E);
8574 }
8575 if (auto It = this->Params.find(PVD); It != this->Params.end()) {
8576 if (IsReference || !It->second.IsPtr)
8577 return this->emitGetParam(classifyPrim(E), It->second.Index, E);
8578
8579 return this->emitGetPtrParam(It->second.Index, E);
8580 }
8581
8582 if (!Ctx.getLangOpts().CPlusPlus23 && IsReference && !Locals.contains(D))
8583 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8584 /*InitializerFailed=*/false, E);
8585 }
8586
8587 // Local variables.
8588 if (auto It = Locals.find(D); It != Locals.end()) {
8589 const unsigned Offset = It->second.Offset;
8590 if (IsReference) {
8591 assert(classifyPrim(E) == PT_Ptr);
8592 return this->emitGetRefLocal(Offset, E) && maybePopPtr();
8593 }
8594 return this->emitGetPtrLocal(Offset, E) && maybePopPtr();
8595 }
8596 // Global variables.
8597 if (auto GlobalIndex = P.getGlobal(D)) {
8598 if (IsReference) {
8599 if (!Ctx.getLangOpts().CPlusPlus11)
8600 return this->emitGetGlobal(classifyPrim(E), *GlobalIndex, E);
8601 if (!Ctx.getLangOpts().CPlusPlus23)
8602 return this->emitGetGlobalUnchecked(classifyPrim(E), *GlobalIndex, E);
8603
8604 return this->emitGetRefGlobal(*GlobalIndex, E) && maybePopPtr();
8605 }
8606
8607 return this->emitGetPtrGlobal(*GlobalIndex, E) && maybePopPtr();
8608 }
8609
8610 // In case we need to re-visit a declaration.
8611 auto revisit = [&](const VarDecl *VD,
8612 bool IsConstexprUnknown = true) -> bool {
8614 IsConstexprUnknown);
8615 if constexpr (std::is_same_v<Emitter, EvalEmitter>) {
8616 if (!this->emitPushCC(VD->hasConstantInitialization(), E))
8617 return false;
8618 }
8619 auto VarState = this->visitDecl(VD);
8620
8621 if constexpr (std::is_same_v<Emitter, EvalEmitter>) {
8622 if (!this->emitPopCC(E))
8623 return false;
8624 }
8625
8626 if (VarState.notCreated())
8627 return true;
8628 if (!VarState)
8629 return false;
8630 // Retry.
8631 return this->visitDeclRef(D, E);
8632 };
8633
8634 if constexpr (!std::is_same_v<Emitter, EvalEmitter>) {
8635 // Lambda captures.
8636 if (auto It = this->LambdaCaptures.find(D);
8637 It != this->LambdaCaptures.end()) {
8638 auto [Offset, IsPtr] = It->second;
8639
8640 if (IsPtr)
8641 return this->emitGetThisFieldPtr(Offset, E) && maybePopPtr();
8642 return this->emitGetPtrThisField(Offset, E) && maybePopPtr();
8643 }
8644 }
8645
8646 if (const auto *DRE = dyn_cast<DeclRefExpr>(E);
8647 DRE && DRE->refersToEnclosingVariableOrCapture()) {
8648 if (const auto *VD = dyn_cast<VarDecl>(D); VD && VD->isInitCapture())
8649 return revisit(VD);
8650 }
8651
8652 if (const auto *BD = dyn_cast<BindingDecl>(D))
8653 return this->delegate(BD->getBinding());
8654
8655 // Avoid infinite recursion.
8656 if (D == InitializingDecl) {
8657 if (DiscardResult)
8658 return true;
8659 return this->emitDummyPtr(D, E);
8660 }
8661
8662 // Try to lazily visit (or emit dummy pointers for) declarations
8663 // we haven't seen yet.
8664 const auto *VD = dyn_cast<VarDecl>(D);
8665 if (!VD)
8666 return this->emitError(E);
8667
8668 // For C.
8669 if (!Ctx.getLangOpts().CPlusPlus) {
8670 if (VD->getInit() && !VD->getInit()->isValueDependent() &&
8671 DeclType.isConstant(Ctx.getASTContext()) && !VD->isWeak() &&
8672 VD->evaluateValue())
8673 return revisit(VD, /*IsConstexprUnknown=*/false);
8674
8675 if (DiscardResult)
8676 return true;
8677 return this->emitDummyPtr(D, E);
8678 }
8679
8680 // ... and C++.
8681 const auto typeShouldBeVisited = [&](QualType T) -> bool {
8682 if (T.isConstant(Ctx.getASTContext()))
8683 return true;
8684 return T->isReferenceType();
8685 };
8686
8687 if ((VD->hasGlobalStorage() || VD->isStaticDataMember()) &&
8688 typeShouldBeVisited(DeclType)) {
8689 if (const Expr *Init = VD->getAnyInitializer();
8690 Init && !Init->isValueDependent()) {
8691 // Whether or not the evaluation is successul doesn't really matter
8692 // here -- we will create a global variable in any case, and that
8693 // will have the state of initializer evaluation attached.
8695 (void)Init->EvaluateAsInitializer(Ctx.getASTContext(), VD, Result, true);
8696 return this->visitDeclRef(D, E);
8697 }
8698 return revisit(VD, !VD->isConstexpr() && DeclType->isReferenceType());
8699 }
8700
8701 // FIXME: The evaluateValue() check here is a little ridiculous, since
8702 // it will ultimately call into Context::evaluateAsInitializer(). In
8703 // other words, we're evaluating the initializer, just to know if we can
8704 // evaluate the initializer.
8705 if (VD->isLocalVarDecl() && typeShouldBeVisited(DeclType) && VD->getInit() &&
8706 !VD->getInit()->isValueDependent()) {
8707 if (VD->evaluateValue()) {
8708 bool IsConstexprUnknown = !DeclType.isConstant(Ctx.getASTContext()) &&
8709 !DeclType->isReferenceType();
8710 // Revisit the variable declaration, but make sure it's associated with a
8711 // different evaluation, so e.g. mutable reads don't work on it.
8712 EvalIDScope _(Ctx);
8713 return revisit(VD, IsConstexprUnknown);
8714 } else if (Ctx.getLangOpts().CPlusPlus23 && IsReference)
8715 return revisit(VD, /*IsConstexprUnknown=*/true);
8716
8717 if (IsReference)
8718 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8719 /*InitializerFailed=*/true, E);
8720 }
8721
8722 if (DiscardResult)
8723 return true;
8724 return this->emitDummyPtr(
8725 D, E, Ctx.getLangOpts().CPlusPlus23 && DeclType->isReferenceType());
8726}
8727
8728template <class Emitter>
8730 const auto *D = E->getDecl();
8731 return this->visitDeclRef(D, E);
8732}
8733
8734template <class Emitter>
8736 const DesignatedInitUpdateExpr *E) {
8737 if (!this->visitInitializer(E->getBase()))
8738 return false;
8739 return this->visitInitializer(E->getUpdater());
8740}
8741
8742template <class Emitter> bool Compiler<Emitter>::emitCleanup() {
8743 for (VariableScope<Emitter> *C = VarScope; C; C = C->getParent()) {
8744 if (!C->destroyLocals())
8745 return false;
8746 }
8747 return true;
8748}
8749
8750template <class Emitter>
8751unsigned Compiler<Emitter>::collectBaseOffset(const QualType BaseType,
8752 const QualType DerivedType) {
8753 const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
8754 if (const auto *R = Ty->getPointeeCXXRecordDecl())
8755 return R;
8756 return Ty->getAsCXXRecordDecl();
8757 };
8758 const CXXRecordDecl *BaseDecl = extractRecordDecl(BaseType);
8759 const CXXRecordDecl *DerivedDecl = extractRecordDecl(DerivedType);
8760
8761 return Ctx.collectBaseOffset(BaseDecl, DerivedDecl);
8762}
8763
8764/// Emit casts from a PrimType to another PrimType.
8765template <class Emitter>
8766bool Compiler<Emitter>::emitPrimCast(PrimType FromT, PrimType ToT,
8767 QualType ToQT, const Expr *E) {
8768
8769 if (FromT == PT_Float) {
8770 // Floating to floating.
8771 if (ToT == PT_Float) {
8772 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
8773 return this->emitCastFP(ToSem, getRoundingMode(E), E);
8774 }
8775
8776 if (ToT == PT_IntAP)
8777 return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(ToQT),
8778 getFPOptions(E), E);
8779 if (ToT == PT_IntAPS)
8780 return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(ToQT),
8781 getFPOptions(E), E);
8782
8783 // Float to integral.
8784 if (isIntegerOrBoolType(ToT) || ToT == PT_Bool)
8785 return this->emitCastFloatingIntegral(ToT, getFPOptions(E), E);
8786 }
8787
8788 if (isIntegerOrBoolType(FromT) || FromT == PT_Bool) {
8789 if (ToT == PT_IntAP)
8790 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
8791 if (ToT == PT_IntAPS)
8792 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
8793
8794 // Integral to integral.
8795 if (isIntegerOrBoolType(ToT) || ToT == PT_Bool)
8796 return FromT != ToT ? this->emitCast(FromT, ToT, E) : true;
8797
8798 if (ToT == PT_Float) {
8799 // Integral to floating.
8800 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
8801 return this->emitCastIntegralFloating(FromT, ToSem, getFPOptions(E), E);
8802 }
8803 }
8804
8805 return false;
8806}
8807
8808template <class Emitter>
8809bool Compiler<Emitter>::emitIntegralCast(PrimType FromT, PrimType ToT,
8810 QualType ToQT, const Expr *E) {
8811 assert(FromT != ToT);
8812
8813 if (ToT == PT_IntAP)
8814 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
8815 if (ToT == PT_IntAPS)
8816 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
8817
8818 return this->emitCast(FromT, ToT, E);
8819}
8820
8821/// Emits __real(SubExpr)
8822template <class Emitter>
8823bool Compiler<Emitter>::emitComplexReal(const Expr *SubExpr) {
8824 assert(SubExpr->getType()->isAnyComplexType());
8825
8826 if (DiscardResult)
8827 return this->discard(SubExpr);
8828
8829 if (!this->visit(SubExpr))
8830 return false;
8831 if (SubExpr->isLValue()) {
8832 if (!this->emitConstUint8(0, SubExpr))
8833 return false;
8834 return this->emitArrayElemPtrPopUint8(SubExpr);
8835 }
8836
8837 // Rvalue, load the actual element.
8838 return this->emitArrayElemPop(classifyComplexElementType(SubExpr->getType()),
8839 0, SubExpr);
8840}
8841
8842template <class Emitter>
8843bool Compiler<Emitter>::emitComplexBoolCast(const Expr *E) {
8844 assert(!DiscardResult);
8845 PrimType ElemT = classifyComplexElementType(E->getType());
8846 // We emit the expression (__real(E) != 0 || __imag(E) != 0)
8847 // for us, that means (bool)E[0] || (bool)E[1]
8848 if (!this->emitArrayElem(ElemT, 0, E))
8849 return false;
8850 if (ElemT == PT_Float) {
8851 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
8852 return false;
8853 } else {
8854 if (!this->emitCast(ElemT, PT_Bool, E))
8855 return false;
8856 }
8857
8858 // We now have the bool value of E[0] on the stack.
8859 LabelTy LabelTrue = this->getLabel();
8860 if (!this->jumpTrue(LabelTrue, E))
8861 return false;
8862
8863 if (!this->emitArrayElemPop(ElemT, 1, E))
8864 return false;
8865 if (ElemT == PT_Float) {
8866 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
8867 return false;
8868 } else {
8869 if (!this->emitCast(ElemT, PT_Bool, E))
8870 return false;
8871 }
8872 // Leave the boolean value of E[1] on the stack.
8873 LabelTy EndLabel = this->getLabel();
8874 this->jump(EndLabel, E);
8875
8876 this->emitLabel(LabelTrue);
8877 if (!this->emitPopPtr(E))
8878 return false;
8879 if (!this->emitConstBool(true, E))
8880 return false;
8881
8882 this->fallthrough(EndLabel);
8883 this->emitLabel(EndLabel);
8884
8885 return true;
8886}
8887
8888template <class Emitter>
8889bool Compiler<Emitter>::emitComplexComparison(const Expr *LHS, const Expr *RHS,
8890 const BinaryOperator *E) {
8891 assert(E->isComparisonOp());
8892 assert(!Initializing);
8893 if (DiscardResult)
8894 return this->discard(LHS) && this->discard(RHS);
8895
8896 PrimType ElemT;
8897 bool LHSIsComplex;
8898 unsigned LHSOffset;
8899 if (LHS->getType()->isAnyComplexType()) {
8900 LHSIsComplex = true;
8901 ElemT = classifyComplexElementType(LHS->getType());
8902 LHSOffset = allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true);
8903 if (!this->visit(LHS))
8904 return false;
8905 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
8906 return false;
8907 } else {
8908 LHSIsComplex = false;
8909 PrimType LHST = classifyPrim(LHS->getType());
8910 LHSOffset = this->allocateLocalPrimitive(LHS, LHST, /*IsConst=*/true);
8911 if (!this->visit(LHS))
8912 return false;
8913 if (!this->emitSetLocal(LHST, LHSOffset, E))
8914 return false;
8915 }
8916
8917 bool RHSIsComplex;
8918 unsigned RHSOffset;
8919 if (RHS->getType()->isAnyComplexType()) {
8920 RHSIsComplex = true;
8921 ElemT = classifyComplexElementType(RHS->getType());
8922 RHSOffset = allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true);
8923 if (!this->visit(RHS))
8924 return false;
8925 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
8926 return false;
8927 } else {
8928 RHSIsComplex = false;
8929 PrimType RHST = classifyPrim(RHS->getType());
8930 RHSOffset = this->allocateLocalPrimitive(RHS, RHST, /*IsConst=*/true);
8931 if (!this->visit(RHS))
8932 return false;
8933 if (!this->emitSetLocal(RHST, RHSOffset, E))
8934 return false;
8935 }
8936
8937 auto getElem = [&](unsigned LocalOffset, unsigned Index,
8938 bool IsComplex) -> bool {
8939 if (IsComplex) {
8940 if (!this->emitGetLocal(PT_Ptr, LocalOffset, E))
8941 return false;
8942 return this->emitArrayElemPop(ElemT, Index, E);
8943 }
8944 return this->emitGetLocal(ElemT, LocalOffset, E);
8945 };
8946
8947 for (unsigned I = 0; I != 2; ++I) {
8948 // Get both values.
8949 if (!getElem(LHSOffset, I, LHSIsComplex))
8950 return false;
8951 if (!getElem(RHSOffset, I, RHSIsComplex))
8952 return false;
8953 // And compare them.
8954 if (!this->emitEQ(ElemT, E))
8955 return false;
8956
8957 if (!this->emitCastBoolUint8(E))
8958 return false;
8959 }
8960
8961 // We now have two bool values on the stack. Compare those.
8962 if (!this->emitAddUint8(E))
8963 return false;
8964 if (!this->emitConstUint8(2, E))
8965 return false;
8966
8967 if (E->getOpcode() == BO_EQ) {
8968 if (!this->emitEQUint8(E))
8969 return false;
8970 } else if (E->getOpcode() == BO_NE) {
8971 if (!this->emitNEUint8(E))
8972 return false;
8973 } else
8974 return false;
8975
8976 // In C, this returns an int.
8977 if (PrimType ResT = classifyPrim(E->getType()); ResT != PT_Bool)
8978 return this->emitCast(PT_Bool, ResT, E);
8979 return true;
8980}
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>::emitRecordDestructionPop(const Record *R,
8987 SourceInfo Loc) {
8988 assert(R);
8989 assert(!R->hasTrivialDtor());
8990 const CXXDestructorDecl *Dtor = R->getDestructor();
8991 assert(Dtor);
8992 const Function *DtorFunc = getFunction(Dtor);
8993 if (!DtorFunc)
8994 return false;
8995 assert(DtorFunc->hasThisPointer());
8996 assert(DtorFunc->getNumParams() == 1);
8997 return this->emitCall(DtorFunc, 0, Loc);
8998}
8999/// When calling this, we have a pointer of the local-to-destroy
9000/// on the stack.
9001/// Emit destruction of record types (or arrays of record types).
9002template <class Emitter>
9003bool Compiler<Emitter>::emitDestructionPop(const Descriptor *Desc,
9004 SourceInfo Loc) {
9005 assert(Desc);
9006 assert(!Desc->hasTrivialDtor());
9007
9008 // Arrays.
9009 if (Desc->isArray()) {
9010 const Descriptor *ElemDesc = Desc->ElemDesc;
9011 assert(ElemDesc);
9012
9013 unsigned N = Desc->getNumElems();
9014 if (N == 0)
9015 return this->emitPopPtr(Loc);
9016
9017 for (ssize_t I = N - 1; I >= 1; --I) {
9018 if (!this->emitConstUint64(I, Loc))
9019 return false;
9020 if (!this->emitArrayElemPtrUint64(Loc))
9021 return false;
9022 if (!this->emitDestructionPop(ElemDesc, Loc))
9023 return false;
9024 }
9025 // Last iteration, removes the instance pointer from the stack.
9026 if (!this->emitConstUint64(0, Loc))
9027 return false;
9028 if (!this->emitArrayElemPtrPopUint64(Loc))
9029 return false;
9030 return this->emitDestructionPop(ElemDesc, Loc);
9031 }
9032
9033 assert(Desc->ElemRecord);
9034 assert(!Desc->ElemRecord->hasTrivialDtor());
9035 return this->emitRecordDestructionPop(Desc->ElemRecord, Loc);
9036}
9037
9038/// Create a dummy pointer for the given decl (or expr) and
9039/// push a pointer to it on the stack.
9040template <class Emitter>
9041bool Compiler<Emitter>::emitDummyPtr(DeclOrExpr D, const Expr *E, bool CU) {
9042 assert(!DiscardResult && "Should've been checked before");
9043 return this->emitGetOpaquePtr(D, CU, E);
9044}
9045
9046template <class Emitter>
9047bool Compiler<Emitter>::emitFloat(const APFloat &F, SourceInfo Info) {
9048 if (Floating::singleWord(F.getSemantics()))
9049 return this->emitConstFloat(Floating(F), Info);
9050
9051 APInt I = F.bitcastToAPInt();
9052 return this->emitConstFloat(
9053 Floating(const_cast<uint64_t *>(I.getRawData()),
9054 llvm::APFloatBase::SemanticsToEnum(F.getSemantics())),
9055 Info);
9056}
9057
9058// This function is constexpr if and only if To, From, and the types of
9059// all subobjects of To and From are types T such that...
9060// (3.1) - is_union_v<T> is false;
9061// (3.2) - is_pointer_v<T> is false;
9062// (3.3) - is_member_pointer_v<T> is false;
9063// (3.4) - is_volatile_v<T> is false; and
9064// (3.5) - T has no non-static data members of reference type
9065template <class Emitter>
9066bool Compiler<Emitter>::emitBuiltinBitCast(const CastExpr *E) {
9067 const Expr *SubExpr = E->getSubExpr();
9068 QualType FromType = SubExpr->getType();
9069 QualType ToType = E->getType();
9070 OptPrimType ToT = classify(ToType);
9071
9072 assert(!ToType->isReferenceType());
9073
9074 // Prepare storage for the result in case we discard.
9075 if (DiscardResult && !Initializing && !ToT) {
9076 UnsignedOrNone LocalIndex = allocateLocal(E);
9077 if (!LocalIndex)
9078 return false;
9079 if (!this->emitGetPtrLocal(*LocalIndex, E))
9080 return false;
9081 }
9082
9083 // Get a pointer to the value-to-cast on the stack.
9084 // For CK_LValueToRValueBitCast, this is always an lvalue and
9085 // we later assume it to be one (i.e. a PT_Ptr). However,
9086 // we call this function for other utility methods where
9087 // a bitcast might be useful, so convert it to a PT_Ptr in that case.
9088 if (SubExpr->isGLValue() || FromType->isVectorType()) {
9089 if (!this->visit(SubExpr))
9090 return false;
9091 } else if (OptPrimType FromT = classify(SubExpr)) {
9092 unsigned TempOffset =
9093 allocateLocalPrimitive(SubExpr, *FromT, /*IsConst=*/true);
9094 if (!this->visit(SubExpr))
9095 return false;
9096 if (!this->emitSetLocal(*FromT, TempOffset, E))
9097 return false;
9098 if (!this->emitGetPtrLocal(TempOffset, E))
9099 return false;
9100 } else {
9101 return false;
9102 }
9103
9104 if (!ToT) {
9105 if (!this->emitBitCast(E))
9106 return false;
9107 return DiscardResult ? this->emitPopPtr(E) : true;
9108 }
9109 assert(ToT);
9110
9111 const llvm::fltSemantics *TargetSemantics = nullptr;
9112 if (ToT == PT_Float)
9113 TargetSemantics = &Ctx.getFloatSemantics(ToType);
9114
9115 // Conversion to a primitive type. FromType can be another
9116 // primitive type, or a record/array.
9117 bool ToTypeIsUChar = (ToType->isSpecificBuiltinType(BuiltinType::UChar) ||
9118 ToType->isSpecificBuiltinType(BuiltinType::Char_U));
9119 uint32_t ResultBitWidth = std::max(Ctx.getBitWidth(ToType), 8u);
9120
9121 if (!this->emitBitCastPrim(*ToT, ToTypeIsUChar || ToType->isStdByteType(),
9122 ResultBitWidth, TargetSemantics,
9123 ToType.getTypePtr(), E))
9124 return false;
9125
9126 if (DiscardResult)
9127 return this->emitPop(*ToT, E);
9128
9129 return true;
9130}
9131
9132/// Replicate a scalar value into every scalar element of an aggregate.
9133/// The scalar is stored in a local at \p SrcOffset and a pointer to the
9134/// destination must be on top of the interpreter stack. Each element receives
9135/// the scalar, cast to its own type.
9136template <class Emitter>
9137bool Compiler<Emitter>::emitHLSLAggregateSplat(PrimType SrcT,
9138 unsigned SrcOffset,
9139 QualType DestType,
9140 const Expr *E) {
9141 // Vectors and matrices are treated as flat sequences of elements.
9142 unsigned NumElems = 0;
9143 QualType ElemType;
9144 if (const auto *VT = DestType->getAs<VectorType>()) {
9145 NumElems = VT->getNumElements();
9146 ElemType = VT->getElementType();
9147 } else if (const auto *MT = DestType->getAs<ConstantMatrixType>()) {
9148 NumElems = MT->getNumElementsFlattened();
9149 ElemType = MT->getElementType();
9150 }
9151 if (NumElems > 0) {
9152 PrimType ElemT = classifyPrim(ElemType);
9153 for (unsigned I = 0; I != NumElems; ++I) {
9154 if (!this->emitGetLocal(SrcT, SrcOffset, E))
9155 return false;
9156 if (!this->emitPrimCast(SrcT, ElemT, ElemType, E))
9157 return false;
9158 if (!this->emitInitElem(ElemT, I, E))
9159 return false;
9160 }
9161 return true;
9162 }
9163
9164 // Arrays: primitive elements are filled directly; composite elements
9165 // require recursion into each sub-aggregate.
9166 if (const auto *AT = DestType->getAsArrayTypeUnsafe()) {
9167 const auto *CAT = cast<ConstantArrayType>(AT);
9168 QualType ArrElemType = CAT->getElementType();
9169 unsigned ArrSize = CAT->getZExtSize();
9170
9171 if (OptPrimType ElemT = classify(ArrElemType)) {
9172 for (unsigned I = 0; I != ArrSize; ++I) {
9173 if (!this->emitGetLocal(SrcT, SrcOffset, E))
9174 return false;
9175 if (!this->emitPrimCast(SrcT, *ElemT, ArrElemType, E))
9176 return false;
9177 if (!this->emitInitElem(*ElemT, I, E))
9178 return false;
9179 }
9180 } else {
9181 for (unsigned I = 0; I != ArrSize; ++I) {
9182 if (!this->emitConstUint32(I, E))
9183 return false;
9184 if (!this->emitArrayElemPtrUint32(E))
9185 return false;
9186 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, ArrElemType, E))
9187 return false;
9188 if (!this->emitFinishInitPop(E))
9189 return false;
9190 }
9191 }
9192 return true;
9193 }
9194
9195 // Records: fill base classes first, then named fields in declaration
9196 // order.
9197 if (DestType->isRecordType()) {
9198 const Record *R = getRecord(DestType);
9199 if (!R)
9200 return false;
9201
9202 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
9203 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
9204 const Record::Base *B = R->getBase(BS.getType());
9205 assert(B);
9206 if (!this->emitGetPtrBase(B->Offset, E))
9207 return false;
9208 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, BS.getType(), E))
9209 return false;
9210 if (!this->emitFinishInitPop(E))
9211 return false;
9212 }
9213 }
9214
9215 for (const Record::Field &F : R->fields()) {
9216 if (F.isUnnamedBitField())
9217 continue;
9218
9219 QualType FieldType = F.Decl->getType();
9220 if (OptPrimType FieldT = F.T) {
9221 if (!this->emitGetLocal(SrcT, SrcOffset, E))
9222 return false;
9223 if (!this->emitPrimCast(SrcT, *FieldT, FieldType, E))
9224 return false;
9225 if (F.isBitField()) {
9226 if (!this->emitInitBitField(*FieldT, F.Offset, F.bitWidth(), E))
9227 return false;
9228 } else {
9229 if (!this->emitInitField(*FieldT, F.Offset, E))
9230 return false;
9231 }
9232 } else {
9233 if (!this->emitGetPtrField(F.Offset, E))
9234 return false;
9235 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, FieldType, E))
9236 return false;
9237 if (!this->emitPopPtr(E))
9238 return false;
9239 }
9240 }
9241 return true;
9242 }
9243
9244 return false;
9245}
9246
9247/// Return the total number of scalar elements in a type. This is used
9248/// to cap how many source elements are extracted during an elementwise cast,
9249/// so we never flatten more than the destination can hold.
9250template <class Emitter>
9251unsigned Compiler<Emitter>::countHLSLFlatElements(QualType Ty) {
9252 // Vector and matrix types are treated as flat sequences of elements.
9253 if (const auto *VT = Ty->getAs<VectorType>())
9254 return VT->getNumElements();
9255 if (const auto *MT = Ty->getAs<ConstantMatrixType>())
9256 return MT->getNumElementsFlattened();
9257 // Arrays: total count is array size * scalar elements per element.
9258 if (const auto *AT = Ty->getAsArrayTypeUnsafe()) {
9259 const auto *CAT = cast<ConstantArrayType>(AT);
9260 return CAT->getZExtSize() * countHLSLFlatElements(CAT->getElementType());
9261 }
9262 // Records: sum scalar element counts of base classes and named fields.
9263 if (Ty->isRecordType()) {
9264 const Record *R = getRecord(Ty);
9265 if (!R)
9266 return 0;
9267 unsigned Count = 0;
9268 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
9269 for (const CXXBaseSpecifier &BS : CXXRD->bases())
9270 Count += countHLSLFlatElements(BS.getType());
9271 }
9272 for (const Record::Field &F : R->fields()) {
9273 if (F.isUnnamedBitField())
9274 continue;
9275 Count += countHLSLFlatElements(F.Decl->getType());
9276 }
9277 return Count;
9278 }
9279 // Scalar primitive types contribute one element.
9280 if (canClassify(Ty))
9281 return 1;
9282 return 0;
9283}
9284
9285/// Walk a source aggregate and extract every scalar element into its own local
9286/// variable. The results are appended to \p Elements in declaration order,
9287/// stopping once \p MaxElements have been collected. A pointer to the
9288/// source aggregate must be stored in the local at \p SrcOffset.
9289template <class Emitter>
9290bool Compiler<Emitter>::emitHLSLFlattenAggregate(
9291 QualType SrcType, unsigned SrcOffset,
9292 SmallVectorImpl<HLSLFlatElement> &Elements, unsigned MaxElements,
9293 const Expr *E) {
9294
9295 // Save a scalar value from the stack into a new local and record it.
9296 auto saveToLocal = [&](PrimType T) -> bool {
9297 unsigned Offset = allocateLocalPrimitive(E, T, /*IsConst=*/true);
9298 if (!this->emitSetLocal(T, Offset, E))
9299 return false;
9300 Elements.push_back({Offset, T});
9301 return true;
9302 };
9303
9304 // Save a pointer from the stack into a new local for later use.
9305 auto savePtrToLocal = [&]() -> UnsignedOrNone {
9306 unsigned Offset = allocateLocalPrimitive(E, PT_Ptr, /*IsConst=*/true);
9307 if (!this->emitSetLocal(PT_Ptr, Offset, E))
9308 return std::nullopt;
9309 return Offset;
9310 };
9311
9312 // Vectors and matrices are flat sequences of elements.
9313 unsigned NumElems = 0;
9314 QualType ElemType;
9315 if (const auto *VT = SrcType->getAs<VectorType>()) {
9316 NumElems = VT->getNumElements();
9317 ElemType = VT->getElementType();
9318 } else if (const auto *MT = SrcType->getAs<ConstantMatrixType>()) {
9319 NumElems = MT->getNumElementsFlattened();
9320 ElemType = MT->getElementType();
9321 }
9322 if (NumElems > 0) {
9323 PrimType ElemT = classifyPrim(ElemType);
9324 for (unsigned I = 0; I != NumElems && Elements.size() < MaxElements; ++I) {
9325 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9326 return false;
9327 if (!this->emitArrayElemPop(ElemT, I, E))
9328 return false;
9329 if (!saveToLocal(ElemT))
9330 return false;
9331 }
9332 return true;
9333 }
9334
9335 // Arrays: primitive elements are extracted directly; composite elements
9336 // require recursion into each sub-aggregate.
9337 if (const auto *AT = SrcType->getAsArrayTypeUnsafe()) {
9338 const auto *CAT = cast<ConstantArrayType>(AT);
9339 QualType ArrElemType = CAT->getElementType();
9340 unsigned ArrSize = CAT->getZExtSize();
9341
9342 if (OptPrimType ElemT = classify(ArrElemType)) {
9343 for (unsigned I = 0; I != ArrSize && Elements.size() < MaxElements; ++I) {
9344 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9345 return false;
9346 if (!this->emitArrayElemPop(*ElemT, I, E))
9347 return false;
9348 if (!saveToLocal(*ElemT))
9349 return false;
9350 }
9351 } else {
9352 for (unsigned I = 0; I != ArrSize && Elements.size() < MaxElements; ++I) {
9353 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9354 return false;
9355 if (!this->emitConstUint32(I, E))
9356 return false;
9357 if (!this->emitArrayElemPtrPopUint32(E))
9358 return false;
9359 UnsignedOrNone ElemPtrOffset = savePtrToLocal();
9360 if (!ElemPtrOffset)
9361 return false;
9362 if (!emitHLSLFlattenAggregate(ArrElemType, *ElemPtrOffset, Elements,
9363 MaxElements, E))
9364 return false;
9365 }
9366 }
9367 return true;
9368 }
9369
9370 // Records: base classes come first, then named fields in declaration
9371 // order.
9372 if (SrcType->isRecordType()) {
9373 const Record *R = getRecord(SrcType);
9374 if (!R)
9375 return false;
9376
9377 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
9378 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
9379 if (Elements.size() >= MaxElements)
9380 break;
9381 const Record::Base *B = R->getBase(BS.getType());
9382 assert(B);
9383 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9384 return false;
9385 if (!this->emitGetPtrBasePop(B->Offset, /*NullOK=*/false, E))
9386 return false;
9387 UnsignedOrNone BasePtrOffset = savePtrToLocal();
9388 if (!BasePtrOffset)
9389 return false;
9390 if (!emitHLSLFlattenAggregate(BS.getType(), *BasePtrOffset, Elements,
9391 MaxElements, E))
9392 return false;
9393 }
9394 }
9395
9396 for (const Record::Field &F : R->fields()) {
9397 if (Elements.size() >= MaxElements)
9398 break;
9399 if (F.isUnnamedBitField())
9400 continue;
9401
9402 QualType FieldType = F.Decl->getType();
9403 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9404 return false;
9405 if (!this->emitGetPtrFieldPop(F.Offset, E))
9406 return false;
9407
9408 if (OptPrimType FieldT = F.T) {
9409 if (!this->emitLoadPop(*FieldT, E))
9410 return false;
9411 if (!saveToLocal(*FieldT))
9412 return false;
9413 } else {
9414 UnsignedOrNone FieldPtrOffset = savePtrToLocal();
9415 if (!FieldPtrOffset)
9416 return false;
9417 if (!emitHLSLFlattenAggregate(FieldType, *FieldPtrOffset, Elements,
9418 MaxElements, E))
9419 return false;
9420 }
9421 }
9422 return true;
9423 }
9424
9425 return false;
9426}
9427
9428/// Populate an HLSL aggregate from a flat list of previously extracted source
9429/// elements, casting each to the corresponding destination element type.
9430/// \p ElemIdx tracks the current position in \p Elements and is advanced as
9431/// elements are consumed. A pointer to the destination must be on top of the
9432/// interpreter stack.
9433template <class Emitter>
9434bool Compiler<Emitter>::emitHLSLConstructAggregate(
9435 QualType DestType, ArrayRef<HLSLFlatElement> Elements, unsigned &ElemIdx,
9436 const Expr *E) {
9437
9438 // Consume the next source element, cast it, and leave it on the stack.
9439 auto loadAndCast = [&](PrimType DestT, QualType DestQT) -> bool {
9440 const auto &Src = Elements[ElemIdx++];
9441 if (!this->emitGetLocal(Src.Type, Src.LocalOffset, E))
9442 return false;
9443 return this->emitPrimCast(Src.Type, DestT, DestQT, E);
9444 };
9445
9446 // Vectors and matrices are flat sequences of elements.
9447 unsigned NumElems = 0;
9448 QualType ElemType;
9449 if (const auto *VT = DestType->getAs<VectorType>()) {
9450 NumElems = VT->getNumElements();
9451 ElemType = VT->getElementType();
9452 } else if (const auto *MT = DestType->getAs<ConstantMatrixType>()) {
9453 NumElems = MT->getNumElementsFlattened();
9454 ElemType = MT->getElementType();
9455 }
9456 if (NumElems > 0) {
9457 PrimType DestElemT = classifyPrim(ElemType);
9458 for (unsigned I = 0; I != NumElems; ++I) {
9459 if (!loadAndCast(DestElemT, ElemType))
9460 return false;
9461 if (!this->emitInitElem(DestElemT, I, E))
9462 return false;
9463 }
9464 return true;
9465 }
9466
9467 // Arrays: primitive elements are filled directly; composite elements
9468 // require recursion into each sub-aggregate.
9469 if (const auto *AT = DestType->getAsArrayTypeUnsafe()) {
9470 const auto *CAT = cast<ConstantArrayType>(AT);
9471 QualType ArrElemType = CAT->getElementType();
9472 unsigned ArrSize = CAT->getZExtSize();
9473
9474 if (OptPrimType ElemT = classify(ArrElemType)) {
9475 for (unsigned I = 0; I != ArrSize; ++I) {
9476 if (!loadAndCast(*ElemT, ArrElemType))
9477 return false;
9478 if (!this->emitInitElem(*ElemT, I, E))
9479 return false;
9480 }
9481 } else {
9482 for (unsigned I = 0; I != ArrSize; ++I) {
9483 if (!this->emitConstUint32(I, E))
9484 return false;
9485 if (!this->emitArrayElemPtrUint32(E))
9486 return false;
9487 if (!emitHLSLConstructAggregate(ArrElemType, Elements, ElemIdx, E))
9488 return false;
9489 if (!this->emitFinishInitPop(E))
9490 return false;
9491 }
9492 }
9493 return true;
9494 }
9495
9496 // Records: base classes come first, then named fields in declaration
9497 // order.
9498 if (DestType->isRecordType()) {
9499 const Record *R = getRecord(DestType);
9500 if (!R)
9501 return false;
9502
9503 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
9504 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
9505 const Record::Base *B = R->getBase(BS.getType());
9506 assert(B);
9507 if (!this->emitGetPtrBase(B->Offset, E))
9508 return false;
9509 if (!emitHLSLConstructAggregate(BS.getType(), Elements, ElemIdx, E))
9510 return false;
9511 if (!this->emitFinishInitPop(E))
9512 return false;
9513 }
9514 }
9515
9516 for (const Record::Field &F : R->fields()) {
9517 if (F.isUnnamedBitField())
9518 continue;
9519
9520 QualType FieldType = F.Decl->getType();
9521 if (OptPrimType FieldT = F.T) {
9522 if (!loadAndCast(*FieldT, FieldType))
9523 return false;
9524 if (F.isBitField()) {
9525 if (!this->emitInitBitField(*FieldT, F.Offset, F.bitWidth(), E))
9526 return false;
9527 } else {
9528 if (!this->emitInitField(*FieldT, F.Offset, E))
9529 return false;
9530 }
9531 } else {
9532 if (!this->emitGetPtrField(F.Offset, E))
9533 return false;
9534 if (!emitHLSLConstructAggregate(FieldType, Elements, ElemIdx, E))
9535 return false;
9536 if (!this->emitPopPtr(E))
9537 return false;
9538 }
9539 }
9540 return true;
9541 }
9542
9543 return false;
9544}
9545
9546namespace clang {
9547namespace interp {
9548
9549template class Compiler<ByteCodeEmitter>;
9550template class Compiler<EvalEmitter>;
9551
9552} // namespace interp
9553} // namespace clang
static bool visitAPValue(const APValue &Value, llvm::function_ref< bool(const APValue &)> Visitor)
Definition APValue.cpp:24
#define V(N, I)
static bool emit(llvm::SmallVectorImpl< std::byte > &Code, const T &Val)
Helper to write bytecode and bail out if 32-bit offsets become invalid.
static void emitCleanup(CIRGenFunction &cgf, cir::CleanupScopeOp cleanupScope, EHScopeStack::Cleanup *cleanup, EHScopeStack::Cleanup::Flags flags, Address activeFlag)
static uint32_t getBitWidth(const Expr *E)
static CharUnits alignOfType(QualType T, const ASTContext &ASTCtx, UnaryExprOrTypeTrait Kind)
#define EMIT_ARITH_OP(OP)
static const Expr * stripDerivedToBaseCasts(const Expr *E)
static bool isTrivialMemoryOperation(const CXXMethodDecl *MD)
static const Expr * stripCheckedDerivedToBaseCasts(const Expr *E)
static bool hasTrivialDefaultCtorParent(const FieldDecl *FD)
static bool initNeedsOverridenLoc(const CXXCtorInitializer *Init)
llvm::APSInt APSInt
Definition Compiler.cpp:26
const Expr * ignorePointerCastsAndParens(const Expr *E)
A more selective version of E->IgnoreParenCasts for tryEvaluateBuiltinObjectSize. This ignores some c...
bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD)
Determine whether a type would actually be read by an lvalue-to-rvalue conversion.
unsigned ConvertBuiltinIDToX86BuiltinID(const ASTContext &Ctx, unsigned BuiltinOp)
Convert a builtin ID to the canonical x86 builtin ID the constant evaluators dispatch on in their x86...
TokenType getType() const
Returns the token's type, e.g.
Result
Implement __builtin_bit_cast and related operations.
llvm::SmallPtrSet< const ParmVarDecl *, 1 > FoundParams
bool VisitDeclRefExpr(const DeclRefExpr *E) override
a trap message and trap category.
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
const LValueBase getLValueBase() const
Definition APValue.cpp:1126
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:691
ArrayRef< LValuePathEntry > getLValuePath() const
Definition APValue.cpp:1146
APSInt & getInt()
Definition APValue.h:573
APValue & getStructField(unsigned i)
Definition APValue.h:736
const FieldDecl * getUnionField() const
Definition APValue.h:757
bool isVector() const
Definition APValue.h:555
APSInt & getComplexIntImag()
Definition APValue.h:611
unsigned getStructNumFields() const
Definition APValue.h:723
bool isComplexInt() const
Definition APValue.h:552
APValue & getStructVirtualBase(unsigned i)
Definition APValue.h:741
bool isArray() const
Definition APValue.h:557
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1216
unsigned getArrayInitializedElts() const
Definition APValue.h:710
bool isFloat() const
Definition APValue.h:550
unsigned getStructNumBases() const
Definition APValue.h:719
unsigned getStructNumVirtualBases() const
Definition APValue.h:727
bool hasLValuePath() const
Definition APValue.cpp:1141
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1209
APValue & getUnionValue()
Definition APValue.h:761
CharUnits & getLValueOffset()
Definition APValue.cpp:1136
bool isComplexFloat() const
Definition APValue.h:553
APValue & getVectorElt(unsigned I)
Definition APValue.h:647
APValue & getArrayFiller()
Definition APValue.h:702
unsigned getVectorLength() const
Definition APValue.h:655
bool isLValue() const
Definition APValue.h:554
bool isIndeterminate() const
Definition APValue.h:546
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1223
bool isMemberPointer() const
Definition APValue.h:560
bool isInt() const
Definition APValue.h:549
unsigned getArraySize() const
Definition APValue.h:714
bool isUnion() const
Definition APValue.h:559
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:165
bool isStruct() const
Definition APValue.h:558
bool isNullPointer() const
Definition APValue.cpp:1162
APSInt & getComplexIntReal()
Definition APValue.h:603
APFloat & getComplexFloatImag()
Definition APValue.h:627
APFloat & getComplexFloatReal()
Definition APValue.h:619
APFloat & getFloat()
Definition APValue.h:587
APValue & getStructBase(unsigned i)
Definition APValue.h:731
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
const LangOptions & getLangOpts() const
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const VariableArrayType * getAsVariableArrayType(QualType T) const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4422
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4600
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4606
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4612
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition Expr.h:4619
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition Expr.h:6107
Represents a loop initializing the elements of an array.
Definition Expr.h:6054
llvm::APInt getArraySize() const
Definition Expr.h:6076
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:6069
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6074
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2790
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2819
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition ExprCXX.h:3011
uint64_t getValue() const
Definition ExprCXX.h:3059
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
QualType getElementType() const
Definition TypeBase.h:3832
Attr - This represents one attribute.
Definition Attr.h:47
Represents an attribute applied to a statement.
Definition Stmt.h:2214
Stmt * getSubStmt()
Definition Stmt.h:2250
ArrayRef< const Attr * > getAttrs() const
Definition Stmt.h:2246
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3526
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4107
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4240
Expr * getLHS() const
Definition Expr.h:4157
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4207
static bool isShiftOp(Opcode Opc)
Definition Expr.h:4195
static bool isCommaOp(Opcode Opc)
Definition Expr.h:4210
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4254
Expr * getRHS() const
Definition Expr.h:4159
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4184
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4243
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4248
Opcode getOpcode() const
Definition Expr.h:4152
static bool isBitwiseOp(Opcode Opc)
Definition Expr.h:4198
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6758
BreakStmt - This represents a break.
Definition Stmt.h:3148
Represents a C++2a __builtin_bit_cast(T, v) expression.
Definition ExprCXX.h:5530
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents binding an expression to a temporary.
Definition ExprCXX.h:1498
const Expr * getSubExpr() const
Definition ExprCXX.h:1520
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition ExprCXX.h:728
bool getValue() const
Definition ExprCXX.h:745
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1622
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1696
arg_range arguments()
Definition ExprCXX.h:1677
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1655
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1616
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1693
Represents a C++ constructor within a class.
Definition DeclCXX.h: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:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3195
Expr * getCallee()
Definition Expr.h:3159
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3203
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3206
arg_range arguments()
Definition Expr.h:3264
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1635
CaseStmt - Represent a case statement.
Definition Stmt.h:1931
Stmt * getSubStmt()
Definition Stmt.h:2044
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3745
path_iterator path_begin()
Definition Expr.h:3815
CastKind getCastKind() const
Definition Expr.h:3789
llvm::iterator_range< path_iterator > path()
Path through the class hierarchy taken by casts between base and derived classes (see implementation ...
Definition Expr.h:3832
const FieldDecl * getTargetUnionField() const
Definition Expr.h:3839
path_iterator path_end()
Definition Expr.h:3816
Expr * getSubExpr()
Definition Expr.h:3795
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static CharUnits One()
Construct a CharUnits quantity of one.
Definition CharUnits.h:55
unsigned getValue() const
Definition Expr.h:1674
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4917
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4953
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3362
QualType getElementType() const
Definition TypeBase.h:3372
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4369
QualType getComputationLHSType() const
Definition Expr.h:4403
QualType getComputationResultType() const
Definition Expr.h:4406
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3674
bool isFileScope() const
Definition Expr.h:3706
const Expr * getInitializer() const
Definition Expr.h:3702
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1751
body_range body()
Definition Stmt.h:1814
Stmt * body_back()
Definition Stmt.h:1819
Represents the specialization of a concept - evaluates to a prvalue of type bool.
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3934
An expression that occurs in a constant context and the result of evaluating the expression.
Definition Expr.h:1127
APValue getAPValueResult() const
Definition Expr.cpp:419
bool hasAPValueResult() const
Definition Expr.h:1202
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4490
ContinueStmt - This represents a continue.
Definition Stmt.h:3132
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition Expr.h:4788
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4878
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2121
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
ValueDecl * getDecl()
Definition Expr.h:1383
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1642
decl_range decls()
Definition Stmt.h:1690
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInvalidDecl() const
Definition DeclBase.h:597
bool hasAttr() const
Definition DeclBase.h:586
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
Stmt * getSubStmt()
Definition Stmt.h:2092
InitListExpr * getUpdater() const
Definition Expr.h:6022
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2843
Stmt * getBody()
Definition Stmt.h:2868
Expr * getCond()
Definition Stmt.h:2861
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
Recursively visit a statement or expression, by dispatching to Traverse*() based on the argument's dy...
const Expr * getBase() const
Definition Expr.h:6667
Represents a reference to emded data.
Definition Expr.h:5204
ChildElementIter< false > begin()
Definition Expr.h:5310
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition ExprCXX.h:3715
This represents one expression.
Definition Expr.h:114
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:85
bool isGLValue() const
Definition Expr.h:289
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3117
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:248
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
bool isPRValue() const
Definition Expr.h:287
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:286
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3728
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition Expr.cpp:3292
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:481
QualType getType() const
Definition Expr.h:146
An expression trait intrinsic.
Definition ExprCXX.h:3084
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6696
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4598
Represents a member of a struct/union/class.
Definition Decl.h:3311
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3547
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1620
llvm::APFloat getValue() const
Definition Expr.h:1711
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2899
Stmt * getInit()
Definition Stmt.h:2914
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1120
Stmt * getBody()
Definition Stmt.h:2943
Expr * getInc()
Definition Stmt.h:2942
Expr * getCond()
Definition Stmt.h:2941
DeclStmt * getConditionVariableDeclStmt()
If this ForStmt has a condition variable, return the faux DeclStmt associated with the creation of th...
Definition Stmt.h:2929
const Expr * getSubExpr() const
Definition Expr.h:1107
Represents a function declaration or definition.
Definition Decl.h:2071
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2944
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3279
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4262
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4250
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3817
QualType getReturnType() const
Definition Decl.h:2992
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2917
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2516
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4386
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:3481
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2524
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3881
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3199
Declaration of a template function.
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, llvm::FoldingSetInsertToken &InsertToken)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition Expr.h:4992
Represents a C11 generic selection.
Definition Expr.h:6268
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition Expr.h:6554
IfStmt - This represents an if/then/else.
Definition Stmt.h:2270
Stmt * getThen()
Definition Stmt.h:2359
Stmt * getInit()
Definition Stmt.h:2420
bool isNonNegatedConsteval() const
Definition Stmt.h:2455
Expr * getCond()
Definition Stmt.h:2347
bool isNegatedConsteval() const
Definition Stmt.h:2459
Stmt * getElse()
Definition Stmt.h:2368
DeclStmt * getConditionVariableDeclStmt()
If this IfStmt has a condition variable, return the faux DeclStmt associated with the creation of tha...
Definition Stmt.h:2403
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1068
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1776
const Expr * getSubExpr() const
Definition Expr.h:1788
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6143
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3618
Describes an C or C++ initializer list.
Definition Expr.h:5377
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5491
ArrayRef< Expr * > inits() const
Definition Expr.h:5441
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1973
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2099
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1432
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
bool isCompatibleWith(ClangABI Version) const
Implicit declaration of a temporary that was materialized by a MaterializeTemporaryExpr and lifetime-...
Definition DeclCXX.h:3338
bool isNamed() const
Definition Stmt.h:3101
const Stmt * getNamedLoopOrSwitch() const
If this is a named break/continue, get the loop or switch statement that this targets.
Definition Stmt.cpp:1535
A global _GUID constant.
Definition DeclCXX.h: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:3433
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3516
Expr * getBase() const
Definition Expr.h:3510
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
This represents a decl that may have a name.
Definition Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
Represents a C++ namespace alias.
Definition DeclCXX.h: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:2596
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2655
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2643
unsigned getNumComponents() const
Definition Expr.h:2651
Helper class for OffsetOfExpr.
Definition Expr.h:2490
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2548
@ Array
An index into an array.
Definition Expr.h:2495
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2544
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1223
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1273
Expr * getSelectedExpr() const
Definition ExprCXX.h:4693
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2251
const Expr * getSubExpr() const
Definition Expr.h:2268
Represents a parameter to a function.
Definition Decl.h:1832
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
[C99 6.4.2.2] - A predefined identifier such as func.
Definition Expr.h:2074
StringLiteral * getFunctionName()
Definition Expr.h:2118
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6890
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6938
ArrayRef< Expr * > semantics()
Definition Expr.h:6962
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h: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:4476
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7589
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3678
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
bool isSatisfied() const
Whether or not the requires clause is satisfied.
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3173
Expr * getRetValue()
Definition Stmt.h:3200
SourceLocation getLocation() const
Definition Expr.h:2224
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:597
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition Expr.h:4712
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4764
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4745
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4751
Represents an expression that computes the length of a parameter pack.
Definition ExprCXX.h:4495
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4569
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition Expr.h:5095
APValue EvaluateInContext(const ASTContext &Ctx, const Expr *DefaultExpr) const
Return the result of evaluating this SourceLocExpr in the specified (and possibly null) default argum...
Definition Expr.cpp:2319
Represents a C++11 static_assert declaration.
Definition DeclCXX.h:4166
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4664
CompoundStmt * getSubStmt()
Definition Expr.h:4681
Stmt - This represents one statement.
Definition Stmt.h:85
StmtClass getStmtClass() const
Definition Stmt.h:1504
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1844
unsigned getLength() const
Definition Expr.h:1969
uint32_t getCodeUnit(size_t I) const
Return the code unit at the given position.
Definition Expr.h:1931
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1198
unsigned getCharByteWidth() const
Definition Expr.h:1971
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4718
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1904
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2520
Expr * getCond()
Definition Stmt.h:2583
Stmt * getBody()
Definition Stmt.h:2595
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1186
Stmt * getInit()
Definition Stmt.h:2600
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2651
DeclStmt * getConditionVariableDeclStmt()
If this SwitchStmt has a condition variable, return the faux DeclStmt associated with the creation of...
Definition Stmt.h:2634
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3868
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3969
bool isUnion() const
Definition Decl.h:4079
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:3713
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2694
QualType getArgumentType() const
Definition Expr.h:2737
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2763
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2726
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
Expr * getSubExpr() const
Definition Expr.h:2354
Opcode getOpcode() const
Definition Expr.h:2349
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2367
Represents C++ using-directive.
Definition DeclCXX.h:3126
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5671
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:934
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1606
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1615
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1308
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1249
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2654
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1216
const Expr * getInit() const
Definition Decl.h:1393
const APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2561
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1276
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1383
Represents a GCC generic vector type.
Definition TypeBase.h:4273
unsigned getNumElements() const
Definition TypeBase.h:4288
QualType getElementType() const
Definition TypeBase.h:4287
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2708
Expr * getCond()
Definition Stmt.h:2760
DeclStmt * getConditionVariableDeclStmt()
If this WhileStmt has a condition variable, return the faux DeclStmt associated with the creation of ...
Definition Stmt.h:2796
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1247
Stmt * getBody()
Definition Stmt.h:2772
ArrayIndexScope(Compiler< Emitter > *Ctx, uint64_t Index)
Definition Compiler.cpp:216
A memory block, either on the stack or in the heap.
Definition Block.h:43
void invokeDtor()
Invokes the Destructor.
Definition Block.h:150
Compilation context for expressions.
Definition Compiler.h:116
llvm::SmallVector< InitLink > InitStack
Definition Compiler.h:503
bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E)
bool VisitCXXDeleteExpr(const CXXDeleteExpr *E)
bool VisitOffsetOfExpr(const OffsetOfExpr *E)
bool visitContinueStmt(const ContinueStmt *S)
bool VisitCharacterLiteral(const CharacterLiteral *E)
bool visitArrayElemInit(unsigned ElemIndex, const Expr *Init, OptPrimType InitT)
Pointer to the array(not the element!) must be on the stack when calling this.
bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E)
bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E)
bool visitInitializerPop(const Expr *E)
Similar, but will also pop the pointer.
bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
bool visitBool(const Expr *E)
Visits an expression and converts it to a boolean.
bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
PrimType classifyPrim(QualType Ty) const
Classifies a known primitive type.
Definition Compiler.h:297
bool VisitTypeTraitExpr(const TypeTraitExpr *E)
bool VisitLambdaExpr(const LambdaExpr *E)
bool VisitMemberExpr(const MemberExpr *E)
llvm::DenseMap< const OpaqueValueExpr *, unsigned > OpaqueExprs
OpaqueValueExpr to location mapping.
Definition Compiler.h:478
bool VisitBinaryOperator(const BinaryOperator *E)
bool visitCXXExpansionStmtInstantiation(const CXXExpansionStmtInstantiation *S)
template for (auto x : {1, 2}) {}
bool visitAttributedStmt(const AttributedStmt *S)
bool VisitPackIndexingExpr(const PackIndexingExpr *E)
bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
bool VisitCallExpr(const CallExpr *E)
std::optional< uint64_t > ArrayIndex
Current argument index. Needed to emit ArrayInitIndexExpr.
Definition Compiler.h:484
bool VisitPseudoObjectExpr(const PseudoObjectExpr *E)
bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E)
bool visitAPValueInitializer(const APValue &Val, SourceInfo Info, QualType T, bool IsCompleteClass=true)
const Function * getFunction(const FunctionDecl *FD)
Returns a function for the given FunctionDecl.
bool VisitFixedPointBinOp(const BinaryOperator *E)
bool VisitCastExpr(const CastExpr *E)
Definition Compiler.cpp:447
bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E)
bool VisitFixedPointUnaryOperator(const UnaryOperator *E)
bool VisitComplexUnaryOperator(const UnaryOperator *E)
llvm::DenseMap< const SwitchCase *, LabelTy > CaseMap
Definition Compiler.h:122
bool VisitBlockExpr(const BlockExpr *E)
bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E)
bool VisitLogicalBinOp(const BinaryOperator *E)
bool visitCompoundStmt(const CompoundStmt *S)
Context & Ctx
Current compilation context.
Definition Compiler.h:139
const VarDecl * InitializingDecl
Definition Compiler.h:501
bool visitDeclRef(const ValueDecl *D, const Expr *E)
Visit the given decl as if we have a reference to it.
bool visitBreakStmt(const BreakStmt *S)
bool visitExpr(const Expr *E, bool DestroyToplevelScope) override
bool visitForStmt(const ForStmt *S)
bool VisitDeclRefExpr(const DeclRefExpr *E)
bool VisitOpaqueValueExpr(const OpaqueValueExpr *E)
bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E)
bool visitAPValue(const APValue &Val, PrimType ValType, SourceInfo Info)
Visit an APValue.
bool VisitStmtExpr(const StmtExpr *E)
bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E)
bool VisitFixedPointLiteral(const FixedPointLiteral *E)
const FunctionDecl * CompilingFunction
Definition Compiler.h:514
bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E)
VarCreationState visitVarDecl(const VarDecl *VD, const Expr *Init, bool Toplevel=false)
Creates and initializes a variable from the given decl.
VariableScope< Emitter > * VarScope
Current scope.
Definition Compiler.h:481
bool visitDeclAndReturn(const VarDecl *VD, const Expr *Init, bool ConstantContext) override
Toplevel visitDeclAndReturn().
bool VisitCXXNewExpr(const CXXNewExpr *E)
bool VisitCompoundAssignOperator(const CompoundAssignOperator *E)
bool visit(const Expr *E) override
Evaluates an expression and places the result on the stack.
bool delegate(const Expr *E)
Just pass evaluation on to E.
bool visitLValueExpr(const Expr *E, bool DestroyToplevelScope) override
bool discard(const Expr *E)
Evaluates an expression for side effects and discards the result.
bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
CaseMap CaseLabels
Switch case mapping.
Definition Compiler.h:510
Record * getRecord(QualType Ty)
Returns a record from a record or pointer type.
bool VisitCXXReflectExpr(const CXXReflectExpr *E)
const RecordType * getRecordTy(QualType Ty)
Returns a record type from a record or pointer type.
bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E)
bool visitInitList(ArrayRef< const Expr * > Inits, const Expr *ArrayFiller, const Expr *E)
bool VisitSizeOfPackExpr(const SizeOfPackExpr *E)
bool VisitPredefinedExpr(const PredefinedExpr *E)
bool VisitSourceLocExpr(const SourceLocExpr *E)
bool visitDeclStmt(const DeclStmt *DS, bool EvaluateConditionDecl=false)
bool registerRedecl(const VarDecl *VD, const APValue &V)
bool emitCleanup()
Emits scope cleanup instructions.
bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E)
bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E)
bool visitInitializer(const Expr *E)
Compiles an initializer.
bool visitDtorCall(const VarDecl *VD, const APValue &Value) override
const Expr * SourceLocDefaultExpr
DefaultInit- or DefaultArgExpr, needed for SourceLocExpr.
Definition Compiler.h:487
bool VisitObjCArrayLiteral(const ObjCArrayLiteral *E)
UnsignedOrNone OptLabelTy
Definition Compiler.h:121
bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E)
bool VisitPointerArithBinOp(const BinaryOperator *E)
Perform addition/subtraction of a pointer and an integer or subtraction of two pointers.
bool visitCallArgs(ArrayRef< const Expr * > Args, const FunctionDecl *FuncDecl, bool Activate, bool IsOperatorCall)
bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E)
bool visitDefaultStmt(const DefaultStmt *S)
bool VisitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E)
bool visitWithSubstitutions(const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This, const Expr *Condition) override
Evaluate the Condition as if it was in the body of Callee.
typename Emitter::LabelTy LabelTy
Definition Compiler.h:119
VarCreationState visitDecl(const VarDecl *VD)
bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E)
bool visitStmt(const Stmt *S)
bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E)
bool VisitVectorUnaryOperator(const UnaryOperator *E)
bool VisitCXXConstructExpr(const CXXConstructExpr *E)
bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
bool VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E)
bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E)
bool VisitRecoveryExpr(const RecoveryExpr *E)
bool VisitRequiresExpr(const RequiresExpr *E)
bool Initializing
Flag inidicating if we're initializing an already created variable.
Definition Compiler.h:500
bool visitReturnStmt(const ReturnStmt *RS)
bool VisitCXXThrowExpr(const CXXThrowExpr *E)
bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
bool VisitChooseExpr(const ChooseExpr *E)
bool visitFunc(const FunctionDecl *F) override
bool visitCXXForRangeStmt(const CXXForRangeStmt *S)
bool visitCaseStmt(const CaseStmt *S)
bool VisitComplexBinOp(const BinaryOperator *E)
llvm::DenseMap< const ValueDecl *, Scope::Local > Locals
Variable to storage mapping.
Definition Compiler.h:475
bool VisitAbstractConditionalOperator(const AbstractConditionalOperator *E)
bool VisitCXXTypeidExpr(const CXXTypeidExpr *E)
UnsignedOrNone allocateTemporary(const Expr *E)
bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinID)
bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E)
OptPrimType ReturnType
Type of the expression returned by the function.
Definition Compiler.h:507
bool VisitUnaryOperator(const UnaryOperator *E)
bool VisitFloatCompoundAssignOperator(const CompoundAssignOperator *E)
OptPrimType classify(const Expr *E) const
Definition Compiler.h:291
llvm::SmallVector< LabelInfo > LabelInfoStack
Stack of label information for loops and switch statements.
Definition Compiler.h:512
bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
bool visitDoStmt(const DoStmt *S)
bool VisitIntegerLiteral(const IntegerLiteral *E)
bool VisitInitListExpr(const InitListExpr *E)
bool VisitVectorBinOp(const BinaryOperator *E)
bool VisitStringLiteral(const StringLiteral *E)
bool VisitParenExpr(const ParenExpr *E)
bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E)
bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E)
bool VisitPointerCompoundAssignOperator(const CompoundAssignOperator *E)
bool DiscardResult
Flag indicating if return value is to be discarded.
Definition Compiler.h:490
bool VisitEmbedExpr(const EmbedExpr *E)
UnsignedOrNone allocateLocal(DeclOrExpr Decl, QualType Ty=QualType(), ScopeKind=ScopeKind::Block)
Allocates a space storing a local given its type.
bool VisitConvertVectorExpr(const ConvertVectorExpr *E)
bool VisitCXXThisExpr(const CXXThisExpr *E)
bool VisitConstantExpr(const ConstantExpr *E)
bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
bool visitSwitchStmt(const SwitchStmt *S)
bool VisitCXXUuidofExpr(const CXXUuidofExpr *E)
bool VisitExprWithCleanups(const ExprWithCleanups *E)
bool visitAsLValue(const Expr *E)
unsigned allocateLocalPrimitive(DeclOrExpr Decl, PrimType Ty, bool IsConst, bool IsVolatile=false, ScopeKind SC=ScopeKind::Block)
Creates a local primitive value.
bool visitWhileStmt(const WhileStmt *S)
bool visitIfStmt(const IfStmt *IS)
bool VisitAddrLabelExpr(const AddrLabelExpr *E)
bool canClassify(const Expr *E) const
Definition Compiler.h:293
bool VisitFloatingLiteral(const FloatingLiteral *E)
Program & P
Program to link to.
Definition Compiler.h:141
bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E)
bool VisitGNUNullExpr(const GNUNullExpr *E)
bool VisitImaginaryLiteral(const ImaginaryLiteral *E)
bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E)
bool visitCXXTryStmt(const CXXTryStmt *S)
static bool isUnevaluatedBuiltin(unsigned ID)
Unevaluated builtins don't get their arguments put on the stack automatically.
Definition Context.cpp:837
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:2790
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:667
A quantity in bits.
const ValueDecl * asValueDecl() const
Definition DeclOrExpr.h:35
const Expr * asExpr() const
Definition DeclOrExpr.h:33
Describes a memory block created by an allocation site.
Definition Descriptor.h:121
unsigned getNumElems() const
Returns the number of elements stored in the block.
Definition Descriptor.h:245
bool isPrimitive() const
Checks if the descriptor is of a primitive.
Definition Descriptor.h:259
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:252
QualType getType() const
const Descriptor *const ElemDesc
Descriptor of the array element.
Definition Descriptor.h:147
bool isPrimitiveArray() const
Checks if the descriptor is of an array of primitives.
Definition Descriptor.h:250
PrimType getPrimType() const
Definition Descriptor.h:230
bool isRecord() const
Checks if the descriptor is of a record.
Definition Descriptor.h:264
const Record *const ElemRecord
Pointer to the record, if block contains records.
Definition Descriptor.h:145
bool isArray() const
Checks if the descriptor is of an array.
Definition Descriptor.h:262
Descriptor used for global variables.
Definition Descriptor.h:48
Information about a local's storage.
Definition Function.h:38
State encapsulating if a the variable creation has been successful, unsuccessful, or no variable has ...
Definition Compiler.h:101
static VarCreationState NotCreated()
Definition Compiler.h:105