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