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