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
3583 if (this->constantFolding())
3584 return false;
3585
3586 UnsignedOrNone GlobalIndex = P.createGlobal(E, Inner->getType());
3587 if (!GlobalIndex)
3588 return false;
3589
3590 const LifetimeExtendedTemporaryDecl *TempDecl =
3592
3593 if (InnerT) {
3594 if (!this->visit(Inner))
3595 return false;
3596
3597 if (IsStatic) {
3598 assert(TempDecl);
3599 if (!this->emitInitGlobalTemp(*InnerT, *GlobalIndex, TempDecl, E))
3600 return false;
3601 } else {
3602 if (!this->emitInitGlobal(*InnerT, *GlobalIndex, E))
3603 return false;
3604 }
3605 return this->emitGetPtrGlobal(*GlobalIndex, E);
3606 }
3607
3608 if (!this->checkLiteralType(Inner))
3609 return false;
3610 // Non-primitive values.
3611 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
3612 return false;
3613 if (!this->visitInitializer(Inner))
3614 return false;
3615 if (IsStatic) {
3616 assert(TempDecl);
3617 return this->emitInitGlobalTempComp(TempDecl, E);
3618 }
3619 return true;
3620 }
3621
3625
3626 // For everyhing else, use local variables.
3627 if (InnerT) {
3628 bool IsConst = Inner->getType().isConstQualified();
3629 bool IsVolatile = Inner->getType().isVolatileQualified();
3630 unsigned LocalIndex =
3631 allocateLocalPrimitive(E, *InnerT, IsConst, IsVolatile, VarScope);
3632 if (!this->VarScope->LocalsAlwaysEnabled &&
3633 !this->emitEnableLocal(LocalIndex, E))
3634 return false;
3635
3636 if (!this->visit(Inner))
3637 return false;
3638 if (!this->emitSetLocal(*InnerT, LocalIndex, E))
3639 return false;
3640
3641 return this->emitGetPtrLocal(LocalIndex, E);
3642 }
3643
3644 if (!this->checkLiteralType(Inner))
3645 return false;
3646
3647 if (UnsignedOrNone LocalIndex =
3648 allocateLocal(E, Inner->getType(), VarScope)) {
3649 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
3650
3651 if (!this->VarScope->LocalsAlwaysEnabled &&
3652 !this->emitEnableLocal(*LocalIndex, E))
3653 return false;
3654
3655 if (!this->emitGetPtrLocal(*LocalIndex, E))
3656 return false;
3657 return this->visitInitializer(Inner);
3658 }
3659 return false;
3660}
3661
3662template <class Emitter>
3664 const CXXBindTemporaryExpr *E) {
3665 const Expr *SubExpr = E->getSubExpr();
3666
3667 if (Initializing)
3668 return this->delegate(SubExpr);
3669
3670 // Make sure we create a temporary even if we're discarding, since that will
3671 // make sure we will also call the destructor.
3672
3673 if (!this->visit(SubExpr))
3674 return false;
3675
3676 if (DiscardResult)
3677 return this->emitPopPtr(E);
3678 return true;
3679}
3680
3681template <class Emitter>
3683 const Expr *Init = E->getInitializer();
3684 if (DiscardResult)
3685 return this->discard(Init);
3686
3687 if (Initializing) {
3688 // We already have a value, just initialize that.
3689 return this->visitInitializer(Init);
3690 }
3691
3692 OptPrimType T = classify(E->getType());
3693 if (E->isFileScope()) {
3694 // Avoid creating a variable if this is a primitive RValue anyway.
3695 if (T && !E->isLValue())
3696 return this->delegate(Init);
3697
3698 UnsignedOrNone GlobalIndex = P.createGlobal(E, E->getType());
3699 if (!GlobalIndex)
3700 return false;
3701
3702 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
3703 return false;
3704
3705 // Since this is a global variable, we might've already seen,
3706 // don't do it again.
3707 if (P.isGlobalInitialized(*GlobalIndex))
3708 return true;
3709
3710 if (T) {
3711 if (!this->visit(Init))
3712 return false;
3713 return this->emitInitGlobal(*T, *GlobalIndex, E);
3714 }
3715
3716 return this->visitInitializer(Init);
3717 }
3718
3719 // Otherwise, use a local variable.
3720 if (T && !E->isLValue()) {
3721 // For primitive types, we just visit the initializer.
3722 return this->delegate(Init);
3723 }
3724
3725 unsigned LocalIndex;
3726 if (T)
3727 LocalIndex = this->allocateLocalPrimitive(Init, *T, /*IsConst=*/false);
3728 else if (UnsignedOrNone MaybeIndex = this->allocateLocal(Init))
3729 LocalIndex = *MaybeIndex;
3730 else
3731 return false;
3732
3733 if (!this->emitGetPtrLocal(LocalIndex, E))
3734 return false;
3735
3736 if (T)
3737 return this->visit(Init) && this->emitInit(*T, E);
3738 return this->visitInitializer(Init);
3739}
3740
3741template <class Emitter>
3743 if (DiscardResult)
3744 return true;
3745 if (E->isStoredAsBoolean()) {
3746 if (E->getType()->isBooleanType())
3747 return this->emitConstBool(E->getBoolValue(), E);
3748 return this->emitConst(E->getBoolValue(), E);
3749 }
3750 if (E->isStoredAsComparisonResult()) {
3751 const ComparisonCategoryInfo &CmpInfo =
3752 Ctx.getASTContext().CompCategories.getInfoForType(E->getType());
3753 const auto Result =
3754 ComparisonCategoryResult(E->getAPValue().getInt().getZExtValue());
3755 const Record *R = getRecord(E->getType());
3756 if (!R || R->getNumFields() == 0)
3757 return false;
3758 const Record::Field *Field = R->getField(0U);
3759 assert(Field->T);
3760 if (!this->emitConst(CmpInfo.getValueInfo(Result)->getIntValue(), *Field->T,
3761 E))
3762 return false;
3763 return this->emitInitField(*Field->T, Field->Offset, E);
3764 }
3765
3767 return this->visitAPValue(E->getAPValue(), T, E);
3768}
3769
3770template <class Emitter>
3772 if (DiscardResult)
3773 return true;
3774 return this->emitConst(E->getValue(), E);
3775}
3776
3777template <class Emitter>
3779 if (DiscardResult)
3780 return true;
3781
3782 assert(Initializing);
3783 const Record *R = P.getOrCreateRecord(E->getLambdaClass());
3784 if (!R)
3785 return false;
3786
3787 auto *CaptureInitIt = E->capture_init_begin();
3788 // Initialize all fields (which represent lambda captures) of the
3789 // record with their initializers.
3790 for (const Record::Field &F : R->fields()) {
3791 const Expr *Init = *CaptureInitIt;
3792 if (!Init || Init->containsErrors())
3793 continue;
3794 ++CaptureInitIt;
3795
3796 if (OptPrimType T = classify(Init)) {
3797 if (!this->visit(Init))
3798 return false;
3799
3800 if (!this->emitInitField(*T, F.Offset, E))
3801 return false;
3802 } else {
3803 if (!this->emitGetPtrField(F.Offset, E))
3804 return false;
3805
3806 if (!this->visitInitializerPop(Init))
3807 return false;
3808 }
3809 }
3810
3811 return true;
3812}
3813
3814template <class Emitter>
3816 if (DiscardResult)
3817 return true;
3818
3819 if (!Initializing)
3820 return this->emitGetStringPtr(E, E);
3821 return this->delegate(E->getFunctionName());
3822}
3823
3824template <class Emitter>
3826 if (E->getSubExpr() && !this->discard(E->getSubExpr()))
3827 return false;
3828
3829 return this->emitInvalid(E);
3830}
3831
3832template <class Emitter>
3834 const CXXReinterpretCastExpr *E) {
3835 const Expr *SubExpr = E->getSubExpr();
3836
3837 OptPrimType FromT = classify(SubExpr);
3838 OptPrimType ToT = classify(E);
3839
3840 if (!FromT || !ToT)
3841 return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, E);
3842
3843 if (FromT == PT_Ptr || ToT == PT_Ptr) {
3846 if (!this->emitInvalidCast(CastKind, /*Fatal=*/false, E))
3847 return false;
3848 if (E->getCastKind() == CK_LValueBitCast)
3849 return this->delegate(SubExpr);
3850 return this->VisitCastExpr(E);
3851 }
3852
3853 // Try to actually do the cast.
3854 bool Fatal = (ToT != FromT);
3855 if (!this->emitInvalidCast(CastKind::Reinterpret, Fatal, E))
3856 return false;
3857
3858 return this->VisitCastExpr(E);
3859}
3860
3861template <class Emitter>
3863 if (!Ctx.getLangOpts().CPlusPlus20) {
3864 if (!this->emitInvalidCast(CastKind::Dynamic, /*Fatal=*/false, E))
3865 return false;
3866 }
3867
3868 if (E->getCastKind() != CK_Dynamic)
3869 return this->VisitCastExpr(E);
3870
3871 QualType DestType = E->getType();
3872 // "target type must be a reference or pointer type to a defined class"
3873 if (DestType->isRecordType()) {
3874 assert(E->isGLValue());
3875 } else {
3876 assert(DestType->isPointerOrReferenceType());
3877 assert(DestType->isVoidPointerType() ||
3878 DestType->getPointeeType()->isRecordType());
3879 DestType = DestType->getPointeeType();
3880 }
3881
3882 if (!this->visit(E->getSubExpr()))
3883 return false;
3884 if (!this->emitDynamicCast(DestType.getTypePtr(),
3885 /*IsReferenceCast=*/E->isGLValue(), E))
3886 return false;
3887
3888 if (DiscardResult)
3889 return this->emitPopPtr(E);
3890 return true;
3891}
3892
3893template <class Emitter>
3895 assert(E->getType()->isBooleanType());
3896
3897 if (DiscardResult)
3898 return true;
3899 return this->emitConstBool(E->getValue(), E);
3900}
3901
3902template <class Emitter>
3904 QualType T = E->getType();
3905 assert(!canClassify(T));
3906
3907 if (T->isRecordType()) {
3908 const CXXConstructorDecl *Ctor = E->getConstructor();
3909
3910 // If we're discarding a construct expression, we still need
3911 // to allocate a variable and call the constructor and destructor.
3912 if (DiscardResult) {
3913 if (Ctor->isTrivial())
3914 return true;
3915 assert(!Initializing);
3916 UnsignedOrNone LocalIndex = allocateLocal(E);
3917
3918 if (!LocalIndex)
3919 return false;
3920
3921 if (!this->emitGetPtrLocal(*LocalIndex, E))
3922 return false;
3923 }
3924
3925 // Trivial copy/move constructor. Avoid copy.
3926 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
3927 Ctor->isTrivial() &&
3928 E->getArg(0)->isTemporaryObject(Ctx.getASTContext(),
3929 T->getAsCXXRecordDecl()))
3930 return this->visitInitializer(E->getArg(0));
3931
3932 // Zero initialization.
3933 bool ZeroInit = E->requiresZeroInitialization();
3934 if (ZeroInit) {
3935 const Record *R = getRecord(E->getType());
3936 if (!R)
3937 return false;
3938
3939 if (!this->visitZeroRecordInitializer(R, E))
3940 return false;
3941
3942 // If the constructor is trivial anyway, we're done.
3943 if (Ctor->isTrivial())
3944 return true;
3945 }
3946
3947 // Trivial default constructors might never be implicitly defined by the
3948 // AST, so we need to special-case them here.
3949 if (Ctor->isTrivial() && Ctor->isDefaultConstructor()) {
3950 if (!this->emitDefaultInit(Ctor, E))
3951 return false;
3952 if (DiscardResult)
3953 return this->emitPopPtr(E);
3954 return true;
3955 }
3956
3957 // Avoid materializing a temporary for an elidable copy/move constructor.
3958 if (!ZeroInit && E->isElidable()) {
3959 const Expr *SrcObj = E->getArg(0);
3960 assert(SrcObj->isTemporaryObject(Ctx.getASTContext(), Ctor->getParent()));
3961 assert(Ctx.getASTContext().hasSameUnqualifiedType(E->getType(),
3962 SrcObj->getType()));
3963 if (const auto *ME = dyn_cast<MaterializeTemporaryExpr>(SrcObj)) {
3964 if (!this->emitCheckFunctionDecl(Ctor, E))
3965 return false;
3966 return this->visitInitializer(ME->getSubExpr());
3967 }
3968 }
3969
3970 const Function *Func = getFunction(Ctor);
3971
3972 if (!Func)
3973 return false;
3974
3975 assert(Func->hasThisPointer());
3976 assert(!Func->hasRVO());
3977
3978 // The This pointer is already on the stack because this is an initializer,
3979 // but we need to dup() so the call() below has its own copy.
3980 if (!this->emitDupPtr(E))
3981 return false;
3982
3983 // Constructor arguments.
3984 for (const auto *Arg : E->arguments()) {
3985 if (!this->visit(Arg))
3986 return false;
3987 }
3988
3989 if (Func->isVariadic()) {
3990 uint32_t VarArgSize = 0;
3991 unsigned NumParams = Func->getNumWrittenParams();
3992 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I) {
3993 VarArgSize +=
3994 align(primSize(classify(E->getArg(I)->getType()).value_or(PT_Ptr)));
3995 }
3996 if (!this->emitCallVar(Func, VarArgSize, E))
3997 return false;
3998 } else {
3999 if (!this->emitCall(Func, 0, E)) {
4000 // When discarding, we don't need the result anyway, so clean up
4001 // the instance dup we did earlier in case surrounding code wants
4002 // to keep evaluating.
4003 if (DiscardResult)
4004 (void)this->emitPopPtr(E);
4005 return false;
4006 }
4007 }
4008
4009 if (DiscardResult)
4010 return this->emitPopPtr(E);
4011 return true;
4012 }
4013
4014 if (T->isArrayType()) {
4015 const Function *Func = getFunction(E->getConstructor());
4016 if (!Func)
4017 return false;
4018
4019 if (!this->emitDupPtr(E))
4020 return false;
4021
4022 std::function<bool(QualType)> initArrayDimension;
4023 initArrayDimension = [&](QualType T) -> bool {
4024 if (!T->isArrayType()) {
4025 // Constructor arguments.
4026 for (const auto *Arg : E->arguments()) {
4027 if (!this->visit(Arg))
4028 return false;
4029 }
4030
4031 return this->emitCall(Func, 0, E);
4032 }
4033
4034 const ConstantArrayType *CAT =
4035 Ctx.getASTContext().getAsConstantArrayType(T);
4036 if (!CAT)
4037 return false;
4038 QualType ElemTy = CAT->getElementType();
4039 unsigned NumElems = CAT->getZExtSize();
4040 for (size_t I = 0; I != NumElems; ++I) {
4041 if (!this->emitConstUint64(I, E))
4042 return false;
4043 if (!this->emitArrayElemPtrUint64(E))
4044 return false;
4045 if (!initArrayDimension(ElemTy))
4046 return false;
4047 }
4048 return this->emitPopPtr(E);
4049 };
4050
4051 return initArrayDimension(E->getType());
4052 }
4053
4054 return false;
4055}
4056
4057template <class Emitter>
4059 if (DiscardResult)
4060 return true;
4061
4062 const APValue Val =
4063 E->EvaluateInContext(Ctx.getASTContext(), SourceLocDefaultExpr);
4064
4065 // Things like __builtin_LINE().
4066 if (E->getType()->isIntegerType()) {
4067 assert(Val.isInt());
4068 const APSInt &I = Val.getInt();
4069 return this->emitConst(I, E);
4070 }
4071 // Otherwise, the APValue is an LValue, with only one element.
4072 // Theoretically, we don't need the APValue at all of course.
4073 assert(E->getType()->isPointerType());
4074 assert(Val.isLValue());
4075 const APValue::LValueBase &Base = Val.getLValueBase();
4076 if (const Expr *LValueExpr = Base.dyn_cast<const Expr *>())
4077 return this->visit(LValueExpr);
4078
4079 // Otherwise, we have a decl (which is the case for
4080 // __builtin_source_location).
4081 assert(Base.is<const ValueDecl *>());
4082 assert(Val.getLValuePath().size() == 0);
4083 const auto *BaseDecl = Base.dyn_cast<const ValueDecl *>();
4084 assert(BaseDecl);
4085
4086 auto *UGCD = cast<UnnamedGlobalConstantDecl>(BaseDecl);
4087
4088 UnsignedOrNone GlobalIndex = P.getOrCreateGlobal(UGCD);
4089 if (!GlobalIndex)
4090 return false;
4091
4092 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
4093 return false;
4094
4095 const Record *R = getRecord(E->getType());
4096 const APValue &V = UGCD->getValue();
4097 for (unsigned I = 0, N = R->getNumFields(); I != N; ++I) {
4098 const Record::Field *F = R->getField(I);
4099 const APValue &FieldValue = V.getStructField(I);
4100
4101 if (!this->visitAPValue(FieldValue, *F->T, E))
4102 return false;
4103 if (!this->emitInitField(*F->T, F->Offset, E))
4104 return false;
4105 }
4106
4107 // Leave the pointer to the global on the stack.
4108 return true;
4109}
4110
4111template <class Emitter>
4113 unsigned N = E->getNumComponents();
4114 if (N == 0)
4115 return false;
4116
4117 for (unsigned I = 0; I != N; ++I) {
4118 const OffsetOfNode &Node = E->getComponent(I);
4119 if (Node.getKind() == OffsetOfNode::Array) {
4120 const Expr *ArrayIndexExpr = E->getIndexExpr(Node.getArrayExprIndex());
4121 PrimType IndexT = classifyPrim(ArrayIndexExpr->getType());
4122
4123 if (DiscardResult) {
4124 if (!this->discard(ArrayIndexExpr))
4125 return false;
4126 continue;
4127 }
4128
4129 if (IndexT == PT_IntAP || IndexT == PT_IntAPS) {
4130 if (!this->visit(ArrayIndexExpr))
4131 return false;
4132 if (!this->emitCastAPToOffsetIndex(IndexT, E))
4133 return false;
4134 continue;
4135 }
4136 if (!this->visit(ArrayIndexExpr))
4137 return false;
4138 // Cast to Sint64.
4139 if (IndexT != PT_Sint64) {
4140 if (!this->emitCast(IndexT, PT_Sint64, E))
4141 return false;
4142 }
4143 }
4144 }
4145
4146 if (DiscardResult)
4147 return true;
4148
4150 return this->emitOffsetOf(T, E, E);
4151}
4152
4153template <class Emitter>
4155 const CXXScalarValueInitExpr *E) {
4156 QualType Ty = E->getType();
4157
4158 if (DiscardResult || Ty->isVoidType())
4159 return true;
4160
4161 if (OptPrimType T = classify(Ty))
4162 return this->visitZeroInitializer(*T, Ty, E);
4163
4164 if (Ty->isAnyComplexType() || Ty->isVectorType()) {
4165 if (!Initializing) {
4166 UnsignedOrNone LocalIndex = allocateLocal(E);
4167 if (!LocalIndex)
4168 return false;
4169 if (!this->emitGetPtrLocal(*LocalIndex, E))
4170 return false;
4171 }
4172
4173 QualType ElemQT;
4174 unsigned NumElems;
4175 if (const auto *CT = Ty->getAs<ComplexType>()) {
4176 NumElems = 2;
4177 ElemQT = CT->getElementType();
4178 } else {
4179 const auto *VT = Ty->castAs<VectorType>();
4180 NumElems = VT->getNumElements();
4181 ElemQT = VT->getElementType();
4182 }
4183
4184 PrimType ElemT = classifyPrim(ElemQT);
4185
4186 // Initialize all fields to 0.
4187 for (unsigned I = 0; I != NumElems; ++I) {
4188 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
4189 return false;
4190 if (!this->emitInitElem(ElemT, I, E))
4191 return false;
4192 }
4193 return true;
4194 }
4195
4196 return false;
4197}
4198
4199template <class Emitter>
4201 return this->emitConst(E->getPackLength(), E);
4202}
4203
4204template <class Emitter>
4209
4210template <class Emitter>
4212 return this->delegate(E->getChosenSubExpr());
4213}
4214
4215template <class Emitter>
4217 if (DiscardResult)
4218 return true;
4219
4220 return this->emitConst(E->getValue(), E);
4221}
4222
4223template <class Emitter>
4225 const CXXInheritedCtorInitExpr *E) {
4226 const CXXConstructorDecl *Ctor = E->getConstructor();
4227 assert(!Ctor->isTrivial() &&
4228 "Trivial CXXInheritedCtorInitExpr, implement. (possible?)");
4229 const Function *F = this->getFunction(Ctor);
4230 if (!F)
4231 return false;
4232 assert(!F->hasRVO());
4233 assert(F->hasThisPointer());
4234
4235 if (!this->emitDupPtr(SourceInfo{}))
4236 return false;
4237
4238 // Forward all arguments of the current function (which should be a
4239 // constructor itself) to the inherited ctor.
4240 // This is necessary because the calling code has pushed the pointer
4241 // of the correct base for us already, but the arguments need
4242 // to come after.
4243 unsigned ParamIndex = 0;
4244 for (const ParmVarDecl *PD : Ctor->parameters()) {
4245 PrimType PT = this->classify(PD->getType()).value_or(PT_Ptr);
4246
4247 if (!this->emitGetParam(PT, ParamIndex, E))
4248 return false;
4249 ++ParamIndex;
4250 }
4251
4252 return this->emitCall(F, 0, E);
4253}
4254
4255// FIXME: This function has become rather unwieldy, especially
4256// the part where we initialize an array allocation of dynamic size.
4257template <class Emitter>
4259 assert(classifyPrim(E->getType()) == PT_Ptr);
4260 const Expr *Init = E->getInitializer();
4261 QualType ElementType = E->getAllocatedType();
4262 OptPrimType ElemT = classify(ElementType);
4263 unsigned PlacementArgs = E->getNumPlacementArgs();
4264 const FunctionDecl *OperatorNew = E->getOperatorNew();
4265 const Expr *PlacementDest = nullptr;
4266 bool IsNoThrow = false;
4267
4268 if (E->containsErrors())
4269 return false;
4270
4271 if (PlacementArgs != 0) {
4272 // FIXME: There is no restriction on this, but it's not clear that any
4273 // other form makes any sense. We get here for cases such as:
4274 //
4275 // new (std::align_val_t{N}) X(int)
4276 //
4277 // (which should presumably be valid only if N is a multiple of
4278 // alignof(int), and in any case can't be deallocated unless N is
4279 // alignof(X) and X has new-extended alignment).
4280 if (PlacementArgs == 1) {
4281 const Expr *Arg1 = E->getPlacementArg(0);
4282 if (OperatorNew->isReservedGlobalPlacementOperator()) {
4283 if (!this->emitCheckPlacementNew(E, E))
4284 return false;
4285 PlacementDest = Arg1;
4286 } else if (
4287 Arg1->getType()->isNothrowT() &&
4288 OperatorNew
4289 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
4290 if (!this->discard(Arg1))
4291 return false;
4292 IsNoThrow = true;
4293 } else {
4294 // Any other placement list is invalid. This includes a user-declared
4295 // allocation function taking std::nothrow_t, e.g. by value.
4296 return this->emitInvalidNewDeleteExpr(E, E);
4297 }
4298 } else {
4299 // Always invalid.
4300 return this->emitInvalid(E);
4301 }
4302 } else if (!OperatorNew
4303 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation())
4304 return this->emitInvalidNewDeleteExpr(E, E);
4305
4306 const Descriptor *Desc;
4307 if (!PlacementDest) {
4308 if (ElemT) {
4309 if (E->isArray())
4310 Desc = nullptr; // We're not going to use it in this case.
4311 else
4312 Desc = P.createDescriptor(E, *ElemT);
4313 } else {
4314 Desc = P.createDescriptor(E, ElementType.getTypePtr(), /*IsConst=*/false,
4315 /*IsTemporary=*/false, /*IsMutable=*/false,
4316 /*IsVolatile=*/false, Init);
4317 }
4318 }
4319
4320 if (E->isArray()) {
4321 std::optional<const Expr *> ArraySizeExpr = E->getArraySize();
4322 if (!ArraySizeExpr)
4323 return false;
4324
4325 const Expr *Stripped = *ArraySizeExpr;
4326 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
4327 Stripped = ICE->getSubExpr())
4328 if (ICE->getCastKind() != CK_NoOp &&
4329 ICE->getCastKind() != CK_IntegralCast)
4330 break;
4331
4332 PrimType SizeT = classifyPrim(Stripped->getType());
4333
4334 // Save evaluated array size to a variable.
4335 unsigned ArrayLen =
4336 allocateLocalPrimitive(Stripped, SizeT, /*IsConst=*/false);
4337 if (!this->visit(Stripped))
4338 return false;
4339 if (!this->emitSetLocal(SizeT, ArrayLen, E))
4340 return false;
4341
4342 if (PlacementDest) {
4343 if (!this->visit(PlacementDest))
4344 return false;
4345 if (!this->emitGetLocal(SizeT, ArrayLen, E))
4346 return false;
4347 if (!this->emitCheckNewTypeMismatchArray(SizeT, E, E))
4348 return false;
4349 } else {
4350 if (!this->emitGetLocal(SizeT, ArrayLen, E))
4351 return false;
4352
4353 if (ElemT) {
4354 // N primitive elements.
4355 if (!this->emitAllocN(SizeT, *ElemT, E, IsNoThrow, E))
4356 return false;
4357 } else {
4358 // N Composite elements.
4359 if (!this->emitAllocCN(SizeT, Desc, IsNoThrow, E))
4360 return false;
4361 }
4362 }
4363
4364 if (Init) {
4365 QualType InitType = Init->getType();
4366 size_t StaticInitElems = 0;
4367 const Expr *DynamicInit = nullptr;
4368 OptPrimType ElemT;
4369
4370 if (const ConstantArrayType *CAT =
4371 Ctx.getASTContext().getAsConstantArrayType(InitType)) {
4372 StaticInitElems = CAT->getZExtSize();
4373 // Initialize the first S element from the initializer.
4374 if (!this->visitInitializer(Init))
4375 return false;
4376
4377 if (const auto *ILE = dyn_cast<InitListExpr>(Init)) {
4378 if (ILE->hasArrayFiller())
4379 DynamicInit = ILE->getArrayFiller();
4380 else if (StaticInitElems > 0 && isa<StringLiteral>(ILE->getInit(0)))
4381 ElemT = classifyPrim(CAT->getElementType());
4382 }
4383 }
4384
4385 // The initializer initializes a certain number of elements, S.
4386 // However, the complete number of elements, N, might be larger than that.
4387 // In this case, we need to get an initializer for the remaining elements.
4388 // There are three cases:
4389 // 1) For the form 'new Struct[n];', the initializer is a
4390 // CXXConstructExpr and its type is an IncompleteArrayType.
4391 // 2) For the form 'new Struct[n]{1,2,3}', the initializer is an
4392 // InitListExpr and the initializer for the remaining elements
4393 // is the array filler.
4394 // 3) StringLiterals don't have an array filler, so we need to zero
4395 // the remaining elements.
4396
4397 if (DynamicInit || ElemT || InitType->isIncompleteArrayType()) {
4398 const Function *CtorFunc = nullptr;
4399 if (const auto *CE = dyn_cast<CXXConstructExpr>(Init)) {
4400 CtorFunc = getFunction(CE->getConstructor());
4401 if (!CtorFunc)
4402 return false;
4403 } else if (!DynamicInit && !ElemT)
4404 DynamicInit = Init;
4405
4406 LabelTy EndLabel = this->getLabel();
4407 LabelTy StartLabel = this->getLabel();
4408
4409 // In the nothrow case, the alloc above might have returned nullptr.
4410 // Don't call any constructors that case.
4411 if (IsNoThrow) {
4412 if (!this->emitDupPtr(E))
4413 return false;
4414 if (!this->emitIsNonNullPtr(E))
4415 return false;
4416 if (!this->jumpFalse(EndLabel, E))
4417 return false;
4418 }
4419
4420 // Create loop variables.
4421 unsigned Iter =
4422 allocateLocalPrimitive(Stripped, SizeT, /*IsConst=*/false);
4423 if (!this->emitConst(StaticInitElems, SizeT, E))
4424 return false;
4425 if (!this->emitSetLocal(SizeT, Iter, E))
4426 return false;
4427
4428 this->fallthrough(StartLabel);
4429 this->emitLabel(StartLabel);
4430 // Condition. Iter < ArrayLen?
4431 if (!this->emitGetLocal(SizeT, Iter, E))
4432 return false;
4433 if (!this->emitGetLocal(SizeT, ArrayLen, E))
4434 return false;
4435 if (!this->emitLT(SizeT, E))
4436 return false;
4437 if (!this->jumpFalse(EndLabel, E))
4438 return false;
4439
4440 // Pointer to the allocated array is already on the stack.
4441 if (!this->emitGetLocal(SizeT, Iter, E))
4442 return false;
4443 if (!this->emitArrayElemPtr(SizeT, E))
4444 return false;
4445
4446 if (isa_and_nonnull<ImplicitValueInitExpr>(DynamicInit) &&
4447 DynamicInit->getType()->isArrayType()) {
4448 QualType ElemType =
4449 DynamicInit->getType()->getAsArrayTypeUnsafe()->getElementType();
4450 if (OptPrimType InitT = classify(ElemType)) {
4451 if (!this->visitZeroInitializer(*InitT, ElemType, E))
4452 return false;
4453 if (!this->emitStorePop(*InitT, E))
4454 return false;
4455 } else {
4456 assert(ElemType->isArrayType());
4457 if (!this->visitZeroArrayInitializer(ElemType, E))
4458 return false;
4459 }
4460 } else if (DynamicInit) {
4461 if (OptPrimType InitT = classify(DynamicInit)) {
4462 if (!this->visit(DynamicInit))
4463 return false;
4464 if (!this->emitStorePop(*InitT, E))
4465 return false;
4466 } else {
4467 if (!this->visitInitializerPop(DynamicInit))
4468 return false;
4469 }
4470 } else if (ElemT) {
4471 if (!this->visitZeroInitializer(
4472 *ElemT, InitType->getAsArrayTypeUnsafe()->getElementType(),
4473 Init))
4474 return false;
4475 if (!this->emitStorePop(*ElemT, E))
4476 return false;
4477 } else {
4478 assert(CtorFunc);
4479 if (!this->emitCall(CtorFunc, 0, E))
4480 return false;
4481 }
4482
4483 // ++Iter;
4484 if (!this->emitGetPtrLocal(Iter, E))
4485 return false;
4486 if (!this->emitIncPop(SizeT, false, E))
4487 return false;
4488
4489 if (!this->jump(StartLabel, E))
4490 return false;
4491
4492 this->fallthrough(EndLabel);
4493 this->emitLabel(EndLabel);
4494 }
4495 }
4496 } else { // Non-array.
4497 if (PlacementDest) {
4498 if (!this->visit(PlacementDest))
4499 return false;
4500 if (!this->emitCheckNewTypeMismatch(E, E))
4501 return false;
4502
4503 } else {
4504 // Allocate just one element.
4505 if (!this->emitAlloc(Desc, E))
4506 return false;
4507 }
4508
4509 if (Init) {
4510 if (ElemT) {
4511 if (!this->visit(Init))
4512 return false;
4513
4514 if (!this->emitInit(*ElemT, E))
4515 return false;
4516 } else {
4517 // Composite.
4518 if (!this->visitInitializer(Init))
4519 return false;
4520 }
4521 }
4522 }
4523
4524 if (DiscardResult)
4525 return this->emitPopPtr(E);
4526
4527 return true;
4528}
4529
4530template <class Emitter>
4532 if (E->containsErrors())
4533 return false;
4534 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
4535
4536 if (!OperatorDelete->isUsableAsGlobalAllocationFunctionInConstantEvaluation())
4537 return this->emitInvalidNewDeleteExpr(E, E);
4538
4539 // Arg must be an lvalue.
4540 if (!this->visit(E->getArgument()))
4541 return false;
4542
4543 return this->emitFree(E->isArrayForm(), E->isGlobalDelete(), E);
4544}
4545
4546template <class Emitter>
4548 if (DiscardResult)
4549 return true;
4550
4551 const Function *Func = nullptr;
4552 if (const Function *F = Ctx.getOrCreateObjCBlock(E))
4553 Func = F;
4554
4555 if (!Func)
4556 return false;
4557 return this->emitGetFnPtr(Func, E);
4558}
4559
4560template <class Emitter>
4562 const Type *TypeInfoType = E->getType().getTypePtr();
4563
4564 auto canonType = [](const Type *T) {
4565 return T->getCanonicalTypeUnqualified().getTypePtr();
4566 };
4567
4568 if (!E->isPotentiallyEvaluated()) {
4569 if (DiscardResult)
4570 return true;
4571
4572 if (E->isTypeOperand())
4573 return this->emitGetTypeid(
4574 canonType(E->getTypeOperand(Ctx.getASTContext()).getTypePtr()),
4575 TypeInfoType, E);
4576
4577 return this->emitGetTypeid(
4578 canonType(E->getExprOperand()->getType().getTypePtr()), TypeInfoType,
4579 E);
4580 }
4581
4582 // Otherwise, we need to evaluate the expression operand.
4583 assert(E->getExprOperand());
4584 assert(E->getExprOperand()->isLValue());
4585
4586 if (!Ctx.getLangOpts().CPlusPlus20 && !this->emitDiagTypeid(E))
4587 return false;
4588
4589 if (!this->visit(E->getExprOperand()))
4590 return false;
4591
4592 if (!this->emitGetTypeidPtr(TypeInfoType, E))
4593 return false;
4594 if (DiscardResult)
4595 return this->emitPopPtr(E);
4596 return true;
4597}
4598
4599template <class Emitter>
4601 const ObjCDictionaryLiteral *E) {
4603 return this->emitDummyPtr(E, E);
4604 return this->emitError(E);
4605}
4606
4607template <class Emitter>
4610 return this->emitDummyPtr(E, E);
4611 return this->emitError(E);
4612}
4613
4614template <class Emitter>
4616 assert(Ctx.getLangOpts().CPlusPlus);
4617 return this->emitConstBool(E->getValue(), E);
4618}
4619
4620template <class Emitter>
4622 if (DiscardResult)
4623 return true;
4624 assert(!Initializing);
4625
4626 const MSGuidDecl *GuidDecl = E->getGuidDecl();
4627 const RecordDecl *RD = GuidDecl->getType()->getAsRecordDecl();
4628 assert(RD);
4629 // If the definiton of the result type is incomplete, just return a dummy.
4630 // If (and when) that is read from, we will fail, but not now.
4631 if (!RD->isCompleteDefinition())
4632 return this->emitDummyPtr(GuidDecl, E);
4633
4634 UnsignedOrNone GlobalIndex = P.getOrCreateGlobal(GuidDecl);
4635 if (!GlobalIndex)
4636 return false;
4637 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
4638 return false;
4639
4640 assert(this->getRecord(E->getType()));
4641
4642 const APValue &V = GuidDecl->getAsAPValue();
4643 if (V.getKind() == APValue::None)
4644 return true;
4645
4646 assert(V.isStruct());
4647 assert(V.getStructNumBases() == 0);
4648 if (!this->visitAPValueInitializer(V, E, E->getType()))
4649 return false;
4650
4651 return this->emitFinishInit(E);
4652}
4653
4654template <class Emitter>
4656 assert(classifyPrim(E->getType()) == PT_Bool);
4657 if (E->isValueDependent())
4658 return false;
4659 if (DiscardResult)
4660 return true;
4661 return this->emitConstBool(E->isSatisfied(), E);
4662}
4663
4664template <class Emitter>
4666 const ConceptSpecializationExpr *E) {
4667 assert(classifyPrim(E->getType()) == PT_Bool);
4668 if (DiscardResult)
4669 return true;
4670 return this->emitConstBool(E->isSatisfied(), E);
4671}
4672
4673template <class Emitter>
4678
4679template <class Emitter>
4681
4682 for (const Expr *SemE : E->semantics()) {
4683 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
4684 if (SemE == E->getResultExpr())
4685 return false;
4686
4687 if (OVE->isUnique())
4688 continue;
4689
4690 if (!this->discard(OVE))
4691 return false;
4692 } else if (SemE == E->getResultExpr()) {
4693 if (!this->delegate(SemE))
4694 return false;
4695 } else {
4696 if (!this->discard(SemE))
4697 return false;
4698 }
4699 }
4700 return true;
4701}
4702
4703template <class Emitter>
4707
4708template <class Emitter>
4710 return this->emitError(E);
4711}
4712
4713template <class Emitter>
4715 assert(E->getType()->isVoidPointerType());
4716 if (DiscardResult)
4717 return true;
4718
4719 return this->emitDummyPtr(E, E);
4720}
4721
4722template <class Emitter>
4723bool Compiler<Emitter>::emitVectorConversion(const Expr *Src, const Expr *E) {
4724 if (Src->containsErrors())
4725 return false;
4726
4727 const auto *VT = E->getType()->castAs<VectorType>();
4728 QualType ElemType = VT->getElementType();
4729 PrimType ElemT = classifyPrim(ElemType);
4730 QualType SrcType = Src->getType();
4731 PrimType SrcElemT = classifyVectorElementType(SrcType);
4732
4733 if (!Initializing) {
4734 UnsignedOrNone LocalIndex = allocateLocal(E);
4735 if (!LocalIndex)
4736 return false;
4737 if (!this->emitGetPtrLocal(*LocalIndex, E))
4738 return false;
4739 }
4740
4741 unsigned SrcOffset =
4742 this->allocateLocalPrimitive(Src, PT_Ptr, /*IsConst=*/true);
4743 if (!this->visit(Src))
4744 return false;
4745 if (!this->emitSetLocal(PT_Ptr, SrcOffset, E))
4746 return false;
4747
4748 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
4749 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
4750 return false;
4751 if (!this->emitArrayElemPop(SrcElemT, I, E))
4752 return false;
4753
4754 // Cast to the desired result element type.
4755 if (SrcElemT != ElemT) {
4756 if (!this->emitPrimCast(SrcElemT, ElemT, ElemType, E))
4757 return false;
4758 } else if (ElemType->isFloatingType() && SrcType != ElemType) {
4759 const auto *TargetSemantics = &Ctx.getFloatSemantics(ElemType);
4760 if (!this->emitCastFP(TargetSemantics, getRoundingMode(E), E))
4761 return false;
4762 }
4763 if (!this->emitInitElem(ElemT, I, E))
4764 return false;
4765 }
4766 return true;
4767}
4768
4769template <class Emitter>
4771 return emitVectorConversion(E->getSrcExpr(), E);
4772}
4773
4774template <class Emitter>
4776 // FIXME: Unary shuffle with mask not currently supported.
4777 if (E->getNumSubExprs() == 2)
4778 return this->emitInvalid(E);
4779
4780 assert(E->getNumSubExprs() > 2);
4781
4782 const Expr *Vecs[] = {E->getExpr(0), E->getExpr(1)};
4783 const VectorType *VT = Vecs[0]->getType()->castAs<VectorType>();
4784 PrimType ElemT = classifyPrim(VT->getElementType());
4785 unsigned NumInputElems = VT->getNumElements();
4786 unsigned NumOutputElems = E->getNumSubExprs() - 2;
4787 assert(NumOutputElems > 0);
4788
4789 if (!Initializing) {
4790 UnsignedOrNone LocalIndex = allocateLocal(E);
4791 if (!LocalIndex)
4792 return false;
4793 if (!this->emitGetPtrLocal(*LocalIndex, E))
4794 return false;
4795 }
4796
4797 // Save both input vectors to a local variable.
4798 unsigned VectorOffsets[2];
4799 for (unsigned I = 0; I != 2; ++I) {
4800 VectorOffsets[I] =
4801 this->allocateLocalPrimitive(Vecs[I], PT_Ptr, /*IsConst=*/true);
4802 if (!this->visit(Vecs[I]))
4803 return false;
4804 if (!this->emitSetLocal(PT_Ptr, VectorOffsets[I], E))
4805 return false;
4806 }
4807 for (unsigned I = 0; I != NumOutputElems; ++I) {
4808 APSInt ShuffleIndex = E->getShuffleMaskIdx(I);
4809 assert(ShuffleIndex >= -1);
4810 if (ShuffleIndex == -1)
4811 return this->emitInvalidShuffleVectorIndex(I, E);
4812
4813 assert(ShuffleIndex < (NumInputElems * 2));
4814 if (!this->emitGetLocal(PT_Ptr,
4815 VectorOffsets[ShuffleIndex >= NumInputElems], E))
4816 return false;
4817 unsigned InputVectorIndex = ShuffleIndex.getZExtValue() % NumInputElems;
4818 if (!this->emitArrayElemPop(ElemT, InputVectorIndex, E))
4819 return false;
4820
4821 if (!this->emitInitElem(ElemT, I, E))
4822 return false;
4823 }
4824
4825 if (DiscardResult)
4826 return this->emitPopPtr(E);
4827
4828 return true;
4829}
4830
4831template <class Emitter>
4833 const ExtVectorElementExpr *E) {
4834 const Expr *Base = E->getBase();
4835 assert(
4836 Base->getType()->isVectorType() ||
4837 Base->getType()->getAs<PointerType>()->getPointeeType()->isVectorType());
4838
4840 E->getEncodedElementAccess(Indices);
4841
4842 if (Indices.size() == 1) {
4843 if (!this->visit(Base))
4844 return false;
4845
4846 if (E->isGLValue()) {
4847 if (!this->emitConstUint32(Indices[0], E))
4848 return false;
4849 return this->emitArrayElemPtrPop(PT_Uint32, E);
4850 }
4851 // Else, also load the value.
4852 return this->emitArrayElemPop(classifyPrim(E->getType()), Indices[0], E);
4853 }
4854
4855 // Create a local variable for the base.
4856 unsigned BaseOffset = allocateLocalPrimitive(Base, PT_Ptr, /*IsConst=*/true);
4857 if (!this->visit(Base))
4858 return false;
4859 if (!this->emitSetLocal(PT_Ptr, BaseOffset, E))
4860 return false;
4861
4862 // Now the vector variable for the return value.
4863 if (!Initializing) {
4864 UnsignedOrNone ResultIndex = allocateLocal(E);
4865 if (!ResultIndex)
4866 return false;
4867 if (!this->emitGetPtrLocal(*ResultIndex, E))
4868 return false;
4869 }
4870
4871 assert(Indices.size() == E->getType()->getAs<VectorType>()->getNumElements());
4872
4873 PrimType ElemT =
4875 uint32_t DstIndex = 0;
4876 for (uint32_t I : Indices) {
4877 if (!this->emitGetLocal(PT_Ptr, BaseOffset, E))
4878 return false;
4879 if (!this->emitArrayElemPop(ElemT, I, E))
4880 return false;
4881 if (!this->emitInitElem(ElemT, DstIndex, E))
4882 return false;
4883 ++DstIndex;
4884 }
4885
4886 // Leave the result pointer on the stack.
4887 assert(!DiscardResult);
4888 return true;
4889}
4890
4891template <class Emitter>
4893 const Expr *SubExpr = E->getSubExpr();
4895 return this->discard(SubExpr) && this->emitInvalid(E);
4896
4897 if (DiscardResult)
4898 return true;
4899
4900 assert(classifyPrim(E) == PT_Ptr);
4901 return this->emitDummyPtr(E, E);
4902}
4903
4904template <class Emitter>
4906 const CXXStdInitializerListExpr *E) {
4907 const Expr *SubExpr = E->getSubExpr();
4909 Ctx.getASTContext().getAsConstantArrayType(SubExpr->getType());
4910 const Record *R = getRecord(E->getType());
4911 assert(Initializing);
4912 assert(SubExpr->isGLValue());
4913
4914 if (!this->visit(SubExpr))
4915 return false;
4916 if (!this->emitConstUint8(0, E))
4917 return false;
4918 if (!this->emitArrayElemPtrPopUint8(E))
4919 return false;
4920 if (!this->emitInitFieldPtr(R->getField(0u)->Offset, E))
4921 return false;
4922
4923 PrimType SecondFieldT = *R->getField(1u)->T;
4924 if (isIntegerOrBoolType(SecondFieldT)) {
4925 if (!this->emitConst(ArrayType->getSize(), SecondFieldT, E))
4926 return false;
4927 return this->emitInitField(SecondFieldT, R->getField(1u)->Offset, E);
4928 }
4929 assert(SecondFieldT == PT_Ptr);
4930
4931 if (!this->emitGetFieldPtr(R->getField(0u)->Offset, E))
4932 return false;
4933 if (!this->emitExpandPtr(E))
4934 return false;
4935 if (!this->emitConst(ArrayType->getSize(), PT_Uint64, E))
4936 return false;
4937 if (!this->emitArrayElemPtrPop(PT_Uint64, E))
4938 return false;
4939 return this->emitInitFieldPtr(R->getField(1u)->Offset, E);
4940}
4941
4942template <class Emitter>
4944 LocalScope<Emitter> BS(this);
4945 llvm::SaveAndRestore StmtExprSAR(this->InStmtExpr, true);
4946
4947 const CompoundStmt *CS = E->getSubStmt();
4948 const Stmt *Result = CS->body_back();
4949 for (const Stmt *S : CS->body()) {
4950 if (S != Result) {
4951 if (!this->visitStmt(S))
4952 return false;
4953 continue;
4954 }
4955
4956 assert(S == Result);
4957 if (const Expr *ResultExpr = dyn_cast<Expr>(S))
4958 return this->delegate(ResultExpr);
4959 if (!this->visitStmt(S))
4960 return false;
4961 return this->emitUnsupported(E);
4962 }
4963
4964 return BS.destroyLocals();
4965}
4966
4967template <class Emitter> bool Compiler<Emitter>::discard(const Expr *E) {
4968 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/true,
4969 /*NewInitializing=*/false, /*ToLValue=*/false);
4970 return this->Visit(E);
4971}
4972
4973template <class Emitter> bool Compiler<Emitter>::delegate(const Expr *E) {
4974 // We're basically doing:
4975 // OptionScope<Emitter> Scope(this, DicardResult, Initializing, ToLValue);
4976 // but that's unnecessary of course.
4977 return this->Visit(E);
4978}
4979
4981 if (const auto *PE = dyn_cast<ParenExpr>(E))
4982 return stripCheckedDerivedToBaseCasts(PE->getSubExpr());
4983
4984 if (const auto *CE = dyn_cast<CastExpr>(E);
4985 CE &&
4986 (CE->getCastKind() == CK_DerivedToBase || CE->getCastKind() == CK_NoOp))
4987 return stripCheckedDerivedToBaseCasts(CE->getSubExpr());
4988
4989 return E;
4990}
4991
4992static const Expr *stripDerivedToBaseCasts(const Expr *E) {
4993 if (const auto *PE = dyn_cast<ParenExpr>(E))
4994 return stripDerivedToBaseCasts(PE->getSubExpr());
4995
4996 if (const auto *CE = dyn_cast<CastExpr>(E);
4997 CE && (CE->getCastKind() == CK_DerivedToBase ||
4998 CE->getCastKind() == CK_UncheckedDerivedToBase ||
4999 CE->getCastKind() == CK_NoOp))
5000 return stripDerivedToBaseCasts(CE->getSubExpr());
5001
5002 return E;
5003}
5004
5005template <class Emitter> bool Compiler<Emitter>::visit(const Expr *E) {
5006 if (E->getType().isNull())
5007 return false;
5008
5009 if (E->getType()->isVoidType())
5010 return this->discard(E);
5011
5012 // Create local variable to hold the return value.
5013 if (!E->isGLValue() && !canClassify(E->getType())) {
5014 UnsignedOrNone LocalIndex = allocateLocal(
5016 if (!LocalIndex)
5017 return false;
5018
5019 if (!this->emitGetPtrLocal(*LocalIndex, E))
5020 return false;
5021 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
5022 return this->visitInitializer(E);
5023 }
5024
5025 // Otherwise,we have a primitive return value, produce the value directly
5026 // and push it on the stack.
5027 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
5028 /*NewInitializing=*/false, /*ToLValue=*/ToLValue);
5029 return this->Visit(E);
5030}
5031
5032template <class Emitter>
5034 assert(!canClassify(E->getType()));
5035
5036 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
5037 /*NewInitializing=*/true, /*ToLValue=*/false);
5038 return this->Visit(E) && this->emitFinishInit(E);
5039}
5040
5041template <class Emitter>
5043 assert(!canClassify(E->getType()));
5044
5045 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
5046 /*NewInitializing=*/true, /*ToLValue=*/false);
5047 return this->Visit(E) && this->emitFinishInitPop(E);
5048}
5049
5050template <class Emitter> bool Compiler<Emitter>::visitAsLValue(const Expr *E) {
5051 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
5052 /*NewInitializing=*/false, /*ToLValue=*/true);
5053 return this->Visit(E);
5054}
5055
5056template <class Emitter> bool Compiler<Emitter>::visitBool(const Expr *E) {
5057 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
5058 /*NewInitializing=*/false, /*ToLValue=*/ToLValue);
5059
5060 OptPrimType T = classify(E->getType());
5061 if (!T) {
5062 // Convert complex values to bool.
5063 if (E->getType()->isAnyComplexType()) {
5064 if (!this->visit(E))
5065 return false;
5066 return this->emitComplexBoolCast(E);
5067 }
5068 return false;
5069 }
5070
5071 if (!this->visit(E))
5072 return false;
5073
5074 if (T == PT_Bool)
5075 return true;
5076
5077 // Convert pointers to bool.
5078 if (T == PT_Ptr)
5079 return this->emitIsNonNullPtr(E);
5080
5081 // Or Floats.
5082 if (T == PT_Float)
5083 return this->emitCastFloatingIntegralBool(getFPOptions(E), E);
5084
5085 // Or anything else we can.
5086 return this->emitCast(*T, PT_Bool, E);
5087}
5088
5089template <class Emitter>
5090bool Compiler<Emitter>::visitZeroInitializer(PrimType T, QualType QT,
5091 const Expr *E) {
5092 if (const auto *AT = QT->getAs<AtomicType>())
5093 QT = AT->getValueType();
5094
5095 switch (T) {
5096 case PT_Bool:
5097 return this->emitZeroBool(E);
5098 case PT_Sint8:
5099 return this->emitZeroSint8(E);
5100 case PT_Uint8:
5101 return this->emitZeroUint8(E);
5102 case PT_Sint16:
5103 return this->emitZeroSint16(E);
5104 case PT_Uint16:
5105 return this->emitZeroUint16(E);
5106 case PT_Sint32:
5107 return this->emitZeroSint32(E);
5108 case PT_Uint32:
5109 return this->emitZeroUint32(E);
5110 case PT_Sint64:
5111 return this->emitZeroSint64(E);
5112 case PT_Uint64:
5113 return this->emitZeroUint64(E);
5114 case PT_IntAP:
5115 return this->emitZeroIntAP(Ctx.getBitWidth(QT), E);
5116 case PT_IntAPS:
5117 return this->emitZeroIntAPS(Ctx.getBitWidth(QT), E);
5118 case PT_Ptr:
5119 return this->emitNullPtr(Ctx.getASTContext().getTargetNullPointerValue(QT),
5120 nullptr, E);
5121 case PT_MemberPtr:
5122 return this->emitNullMemberPtr(0, nullptr, E);
5123 case PT_Float: {
5124 APFloat F = APFloat::getZero(Ctx.getFloatSemantics(QT));
5125 return this->emitFloat(F, E);
5126 }
5127 case PT_FixedPoint: {
5128 auto Sem = Ctx.getASTContext().getFixedPointSemantics(QT);
5129 return this->emitConstFixedPoint(FixedPoint::zero(Sem), E);
5130 }
5131 }
5132 llvm_unreachable("unknown primitive type");
5133}
5134
5135template <class Emitter>
5136bool Compiler<Emitter>::visitZeroRecordInitializer(const Record *R,
5137 const Expr *E,
5138 bool IsCompleteClass) {
5139 assert(E);
5140 assert(R);
5141 // Fields
5142 for (const Record::Field &Field : R->fields()) {
5143 if (Field.isUnnamedBitField())
5144 continue;
5145
5146 const Descriptor *D = Field.Desc;
5147 if (D->isPrimitive()) {
5148 QualType QT = D->getType();
5149 PrimType T = D->getPrimType();
5150 if (!this->visitZeroInitializer(T, QT, E))
5151 return false;
5152 if (R->isUnion()) {
5153 if (!this->emitInitFieldActivate(T, Field.Offset, E))
5154 return false;
5155 break;
5156 }
5157 if (!this->emitInitField(T, Field.Offset, E))
5158 return false;
5159 continue;
5160 }
5161
5162 if (!this->emitGetPtrField(Field.Offset, E))
5163 return false;
5164
5165 if (D->isPrimitiveArray()) {
5166 QualType ET = D->getElemQualType();
5167 PrimType T = D->getPrimType();
5168 for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) {
5169 if (!this->visitZeroInitializer(T, ET, E))
5170 return false;
5171 if (!this->emitInitElem(T, I, E))
5172 return false;
5173 }
5174 } else if (D->isCompositeArray()) {
5175 // Can't be a vector or complex field.
5176 if (!this->visitZeroArrayInitializer(D->getType(), E))
5177 return false;
5178 } else if (D->isRecord()) {
5179 if (!this->visitZeroRecordInitializer(D->ElemRecord, E))
5180 return false;
5181 } else
5182 return false;
5183
5184 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5185 // object's first non-static named data member is zero-initialized
5186 if (R->isUnion()) {
5187 if (!this->emitFinishInitActivatePop(E))
5188 return false;
5189 break;
5190 }
5191 if (!this->emitFinishInitPop(E))
5192 return false;
5193 }
5194
5195 for (const Record::Base &B : R->bases()) {
5196 if (!this->emitGetPtrBase(B.Offset, E))
5197 return false;
5198 if (!this->visitZeroRecordInitializer(B.R, E, /*IsCompleteClass=*/false))
5199 return false;
5200 if (!this->emitFinishInitPop(E))
5201 return false;
5202 }
5203
5204 if (IsCompleteClass) {
5205 for (const Record::Base &B : R->virtual_bases()) {
5206 if (!this->emitGetPtrVirtBase(cast<CXXRecordDecl>(B.R->getDecl()), E))
5207 return false;
5208 if (!this->visitZeroRecordInitializer(B.R, E, /*IsCompleteClass=*/false))
5209 return false;
5210 if (!this->emitFinishInitPop(E))
5211 return false;
5212 }
5213 }
5214
5215 return true;
5216}
5217
5218template <class Emitter>
5219bool Compiler<Emitter>::visitZeroArrayInitializer(QualType T, const Expr *E) {
5220 assert(T->isArrayType() || T->isAnyComplexType() || T->isVectorType());
5221 const ArrayType *AT = T->getAsArrayTypeUnsafe();
5222 QualType ElemType = AT->getElementType();
5223 size_t NumElems = cast<ConstantArrayType>(AT)->getZExtSize();
5224
5225 if (OptPrimType ElemT = classify(ElemType)) {
5226 for (size_t I = 0; I != NumElems; ++I) {
5227 if (!this->visitZeroInitializer(*ElemT, ElemType, E))
5228 return false;
5229 if (!this->emitInitElem(*ElemT, I, E))
5230 return false;
5231 }
5232 return true;
5233 }
5234 if (ElemType->isRecordType()) {
5235 const Record *R = getRecord(ElemType);
5236 if (!R)
5237 return false;
5238
5239 for (size_t I = 0; I != NumElems; ++I) {
5240 if (!this->emitConstUint32(I, E))
5241 return false;
5242 if (!this->emitArrayElemPtr(PT_Uint32, E))
5243 return false;
5244 if (!this->visitZeroRecordInitializer(R, E))
5245 return false;
5246 if (!this->emitPopPtr(E))
5247 return false;
5248 }
5249 return true;
5250 }
5251 if (ElemType->isArrayType()) {
5252 for (size_t I = 0; I != NumElems; ++I) {
5253 if (!this->emitConstUint32(I, E))
5254 return false;
5255 if (!this->emitArrayElemPtr(PT_Uint32, E))
5256 return false;
5257 if (!this->visitZeroArrayInitializer(ElemType, E))
5258 return false;
5259 if (!this->emitPopPtr(E))
5260 return false;
5261 }
5262 return true;
5263 }
5264
5265 return false;
5266}
5267
5268template <class Emitter>
5269bool Compiler<Emitter>::visitAssignment(const Expr *LHS, const Expr *RHS,
5270 const Expr *E) {
5271 if (!canClassify(E->getType()))
5272 return false;
5273
5274 bool NeedsFlip = !isSideEffectFree(RHS);
5275 if (!NeedsFlip) {
5276 if (!this->visit(LHS))
5277 return false;
5278 if (!this->visit(RHS))
5279 return false;
5280 } else {
5281 if (!this->visit(RHS))
5282 return false;
5283 if (!this->visit(LHS))
5284 return false;
5285 }
5286
5287 if (LHS->getType().isVolatileQualified())
5288 return this->emitInvalidStore(LHS->getType().getTypePtr(), E);
5289
5290 // We don't support assignments in C.
5291 if (!Ctx.getLangOpts().CPlusPlus && !this->emitInvalid(E))
5292 return false;
5293
5294 PrimType RHT = classifyPrim(RHS);
5295 bool Activates = refersToUnion(LHS);
5296 bool BitField = LHS->refersToBitField();
5297
5298 if (NeedsFlip && !this->emitFlip(PT_Ptr, RHT, E))
5299 return false;
5300
5301 if (DiscardResult) {
5302 if (BitField && Activates)
5303 return this->emitStoreBitFieldActivatePop(RHT, E);
5304 if (BitField)
5305 return this->emitStoreBitFieldPop(RHT, E);
5306 if (Activates)
5307 return this->emitStoreActivatePop(RHT, E);
5308 // Otherwise, regular non-activating store.
5309 return this->emitStorePop(RHT, E);
5310 }
5311
5312 auto maybeLoad = [&](bool Result) -> bool {
5313 if (!Result)
5314 return false;
5315 // Assignments aren't necessarily lvalues in C.
5316 // Load from them in that case.
5317 if (!E->isLValue())
5318 return this->emitLoadPop(RHT, E);
5319 return true;
5320 };
5321
5322 if (BitField && Activates)
5323 return maybeLoad(this->emitStoreBitFieldActivate(RHT, E));
5324 if (BitField)
5325 return maybeLoad(this->emitStoreBitField(RHT, E));
5326 if (Activates)
5327 return maybeLoad(this->emitStoreActivate(RHT, E));
5328 // Otherwise, regular non-activating store.
5329 return maybeLoad(this->emitStore(RHT, E));
5330}
5331
5332template <class Emitter>
5333template <typename T>
5334bool Compiler<Emitter>::emitConst(T Value, PrimType Ty, SourceInfo Info) {
5335 switch (Ty) {
5336 case PT_Sint8:
5337 return this->emitConstSint8(Value, Info);
5338 case PT_Uint8:
5339 return this->emitConstUint8(Value, Info);
5340 case PT_Sint16:
5341 return this->emitConstSint16(Value, Info);
5342 case PT_Uint16:
5343 return this->emitConstUint16(Value, Info);
5344 case PT_Sint32:
5345 return this->emitConstSint32(Value, Info);
5346 case PT_Uint32:
5347 return this->emitConstUint32(Value, Info);
5348 case PT_Sint64:
5349 return this->emitConstSint64(Value, Info);
5350 case PT_Uint64:
5351 return this->emitConstUint64(Value, Info);
5352 case PT_Bool:
5353 return this->emitConstBool(Value, Info);
5354 case PT_Ptr:
5355 case PT_MemberPtr:
5356 case PT_Float:
5357 case PT_IntAP:
5358 case PT_IntAPS:
5359 case PT_FixedPoint:
5360 llvm_unreachable("Invalid integral type");
5361 break;
5362 }
5363 llvm_unreachable("unknown primitive type");
5364}
5365
5366template <class Emitter>
5367template <typename T>
5368bool Compiler<Emitter>::emitConst(T Value, const Expr *E) {
5369 return this->emitConst(Value, classifyPrim(E->getType()), E);
5370}
5371
5372template <class Emitter>
5373bool Compiler<Emitter>::emitConst(const APSInt &Value, PrimType Ty,
5374 SourceInfo Info) {
5375 if (Ty == PT_IntAPS)
5376 return this->emitConstIntAPS(Value, Info);
5377 if (Ty == PT_IntAP)
5378 return this->emitConstIntAP(Value, Info);
5379
5380 if (Value.isSigned())
5381 return this->emitConst(Value.getSExtValue(), Ty, Info);
5382 return this->emitConst(Value.getZExtValue(), Ty, Info);
5383}
5384
5385template <class Emitter>
5386bool Compiler<Emitter>::emitConst(const APInt &Value, PrimType Ty,
5387 SourceInfo Info) {
5388 if (Ty == PT_IntAPS)
5389 return this->emitConstIntAPS(Value, Info);
5390 if (Ty == PT_IntAP)
5391 return this->emitConstIntAP(Value, Info);
5392
5393 if (isSignedType(Ty))
5394 return this->emitConst(Value.getSExtValue(), Ty, Info);
5395 return this->emitConst(Value.getZExtValue(), Ty, Info);
5396}
5397
5398template <class Emitter>
5399bool Compiler<Emitter>::emitConst(const APSInt &Value, const Expr *E) {
5400 return this->emitConst(Value, classifyPrim(E->getType()), E);
5401}
5402
5403template <class Emitter>
5405 bool IsConst,
5406 bool IsVolatile,
5407 ScopeKind SC) {
5408 // FIXME: There are cases where Src.isExpr() is wrong, e.g.
5409 // (int){12} in C. Consider using Expr::isTemporaryObject() instead
5410 // or isa<MaterializeTemporaryExpr>().
5411 Descriptor *D = P.createDescriptor(Src, Ty, nullptr, IsConst, Src.isExpr(),
5412 /*IsMutable=*/false, IsVolatile);
5414 Scope::Local Local = this->createLocal(D);
5415 if (auto *VD = Src.asValueDecl())
5416 Locals.insert({VD, Local});
5417 VarScope->addForScopeKind(Local, SC);
5418 return Local.Offset;
5419}
5420
5421template <class Emitter>
5423 ScopeKind SC) {
5424 const ValueDecl *Key = nullptr;
5425 const Expr *Init = nullptr;
5426 bool IsTemporary = false;
5427 if (auto *VD = Src.asValueDecl()) {
5428 Key = VD;
5429
5430 if (const auto *VarD = dyn_cast<VarDecl>(VD))
5431 Init = VarD->getInit();
5432 }
5433 if (const auto *E = Src.asExpr()) {
5434 IsTemporary = true;
5435 if (Ty.isNull())
5436 Ty = E->getType();
5437 }
5438
5439 Descriptor *D = P.createDescriptor(
5440 Src, Ty.getTypePtr(), Ty.isConstQualified(), IsTemporary,
5441 /*IsMutable=*/false, /*IsVolatile=*/Ty.isVolatileQualified(), Init);
5442 if (!D)
5443 return std::nullopt;
5445
5446 Scope::Local Local = this->createLocal(D);
5447 if (Key)
5448 Locals.insert({Key, Local});
5449 VarScope->addForScopeKind(Local, SC);
5450 return Local.Offset;
5451}
5452
5453template <class Emitter>
5455 QualType Ty = E->getType();
5456 assert(!Ty->isRecordType());
5457
5458 Descriptor *D = P.createDescriptor(E, Ty.getTypePtr(), Ty.isConstQualified(),
5459 /*IsTemporary=*/true);
5460
5461 if (!D)
5462 return std::nullopt;
5463
5464 Scope::Local Local = this->createLocal(D);
5466 assert(S);
5467 // Attach to topmost scope.
5468 while (S->getParent())
5469 S = S->getParent();
5470 assert(S && !S->getParent());
5471 S->addLocal(Local);
5472 return Local.Offset;
5473}
5474
5475template <class Emitter>
5477 if (const PointerType *PT = dyn_cast<PointerType>(Ty))
5478 return PT->getPointeeType()->getAsCanonical<RecordType>();
5479 return Ty->getAsCanonical<RecordType>();
5480}
5481
5482template <class Emitter> Record *Compiler<Emitter>::getRecord(QualType Ty) {
5483 if (const auto *RecordTy = getRecordTy(Ty))
5484 return getRecord(RecordTy->getDecl()->getDefinitionOrSelf());
5485 return nullptr;
5486}
5487
5488template <class Emitter>
5490 return P.getOrCreateRecord(RD);
5491}
5492
5493template <class Emitter>
5495 return Ctx.getOrCreateFunction(FD);
5496}
5497
5498template <class Emitter>
5499bool Compiler<Emitter>::visitExpr(const Expr *E, bool DestroyToplevelScope) {
5500 assert(E);
5501 assert(!E->getType().isNull());
5503
5504 auto maybeDestroyLocals = [&]() -> bool {
5505 if (DestroyToplevelScope)
5506 return RootScope.destroyLocals() && this->emitCheckAllocations(E);
5507 return this->emitCheckAllocations(E);
5508 };
5509
5510 // Void expressions.
5511 if (E->getType()->isVoidType()) {
5512 if (!visit(E))
5513 return false;
5514 return this->emitRetVoid(E) && maybeDestroyLocals();
5515 }
5516
5517 // Expressions with a primitive return type.
5518 if (OptPrimType T = classify(E)) {
5519 if (!visit(E))
5520 return false;
5521
5522 return this->emitRet(*T, E) && maybeDestroyLocals();
5523 }
5524
5525 // Expressions with a composite return type.
5526 // For us, that means everything we don't
5527 // have a PrimType for.
5528 if (UnsignedOrNone LocalOffset = this->allocateLocal(E)) {
5529 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalOffset));
5530 if (!this->emitGetPtrLocal(*LocalOffset, E))
5531 return false;
5532
5533 if (!visitInitializer(E))
5534 return false;
5535 // We are destroying the locals AFTER the Ret op.
5536 // The Ret op needs to copy the (alive) values, but the
5537 // destructors may still turn the entire expression invalid.
5538 return this->emitRetValue(E) && maybeDestroyLocals();
5539 }
5540
5541 return maybeDestroyLocals() && false;
5542}
5543
5544template <class Emitter>
5546 bool DestroyToplevelScope) {
5547 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
5548 /*NewInitializing=*/false, /*ToLValue=*/true);
5549
5550 return this->visitExpr(E, DestroyToplevelScope);
5551}
5552
5553template <class Emitter>
5555
5556 auto R = this->visitVarDecl(VD, VD->getInit(), /*Toplevel=*/true);
5557
5558 if (R.notCreated())
5559 return R;
5560
5561 if (R)
5562 return true;
5563
5564 if (!R && Context::shouldBeGloballyIndexed(VD)) {
5565 if (auto GlobalIndex = P.getGlobal(VD)) {
5566 Block *GlobalBlock = P.getGlobal(*GlobalIndex);
5567 auto &GD = GlobalBlock->getBlockDesc<GlobalInlineDescriptor>();
5568
5570 GlobalBlock->invokeDtor();
5571 }
5572 }
5573
5574 return R;
5575}
5576
5577/// Toplevel visitDeclAndReturn().
5578/// We get here from evaluateAsInitializer().
5579/// We need to evaluate the initializer and return its value.
5580template <class Emitter>
5582 bool ConstantContext) {
5583 // We only create variables if we're evaluating in a constant context.
5584 // Otherwise, just evaluate the initializer and return it.
5585 if (!ConstantContext) {
5586 DeclScope<Emitter> LS(this, VD);
5587 if (!this->visit(Init))
5588 return false;
5589 return this->emitRet(classify(Init).value_or(PT_Ptr), VD) &&
5590 LS.destroyLocals() && this->emitCheckAllocations(VD);
5591 }
5592
5593 LocalScope<Emitter> VDScope(this);
5594 if (!this->visitVarDecl(VD, Init, /*Toplevel=*/true))
5595 return false;
5596
5597 OptPrimType VarT = classify(VD->getType());
5598 bool IsReference = VD->getType()->isReferenceType();
5600 auto GlobalIndex = P.getGlobal(VD);
5601 assert(GlobalIndex); // visitVarDecl() didn't return false.
5602 if (VarT) {
5603 if (!this->emitGetGlobalUnchecked(*VarT, *GlobalIndex, VD))
5604 return false;
5605 } else {
5606 if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
5607 return false;
5608 }
5609 } else {
5610 auto Local = Locals.find(VD);
5611 assert(Local != Locals.end()); // Same here.
5612 if (VarT) {
5613 if (IsReference) {
5614 if (!this->emitGetRefLocal(Local->second.Offset, VD))
5615 return false;
5616 } else if (!this->emitGetLocal(*VarT, Local->second.Offset, VD))
5617 return false;
5618 } else {
5619 if (!this->emitGetPtrLocal(Local->second.Offset, VD))
5620 return false;
5621 }
5622 }
5623
5624 // Return the value.
5625 if (!this->emitRet(VarT.value_or(PT_Ptr), VD)) {
5626 // If the Ret above failed and this is a global variable. Mark it as
5627 // uninitialized, even if everything else succeeded.
5629 auto GlobalIndex = P.getGlobal(VD);
5630 assert(GlobalIndex);
5631 Block *GlobalBlock = P.getGlobal(*GlobalIndex);
5632 auto &GD = GlobalBlock->getBlockDesc<GlobalInlineDescriptor>();
5633
5635 GlobalBlock->invokeDtor();
5636 }
5637 return false;
5638 }
5639
5640 return VDScope.destroyLocals() && this->emitCheckAllocations(VD);
5641}
5642
5643template <class Emitter>
5645 const Expr *Init,
5646 bool Toplevel) {
5647 QualType VarTy = VD->getType();
5648 // We don't know what to do with these, so just return false.
5649 if (VarTy.isNull())
5650 return false;
5651
5652 // This case is EvalEmitter-only. If we won't create any instructions for the
5653 // initializer anyway, don't bother creating the variable in the first place.
5654 if (!this->isActive())
5656
5657 OptPrimType VarT = classify(VD->getType());
5658
5659 if (Init && Init->isValueDependent())
5660 return false;
5661
5663 auto checkDecl = [&]() -> bool {
5664 bool NeedsOp = !Toplevel && VD->isLocalVarDecl() && VD->isStaticLocal();
5665 return !NeedsOp || this->emitCheckDecl(VD, VD);
5666 };
5667
5669 UnsignedOrNone GlobalIndex = P.getGlobal(VD);
5670 if (GlobalIndex) {
5671 // The global was previously created but the initializer failed.
5672 if (!P.getGlobal(*GlobalIndex)->isInitialized())
5673 return false;
5674 // We've already seen and initialized this global.
5675 if (P.isGlobalInitialized(*GlobalIndex))
5676 return checkDecl();
5677 // The previous attempt at initialization might've been unsuccessful,
5678 // so let's try this one.
5679 } else if ((GlobalIndex =
5680 P.createGlobal(VD, Init, VariablesAreConstexprUnknown))) {
5681 } else {
5682 return false;
5683 }
5684 if (!Init)
5685 return true;
5686
5687 if (!checkDecl())
5688 return false;
5689
5690 if (VarT) {
5691 if (!this->visit(Init))
5692 return false;
5693
5694 return this->emitInitGlobal(*VarT, *GlobalIndex, VD);
5695 }
5696
5697 if (!this->emitGetPtrGlobal(*GlobalIndex, Init))
5698 return false;
5699
5700 if (!this->emitStartInit(Init))
5701 return false;
5702
5703 if (!visitInitializer(Init))
5704 return false;
5705
5706 if (!this->emitEndInit(Init))
5707 return false;
5708
5709 return this->emitFinishInitGlobal(Init);
5710 }
5711 // Local variables.
5713
5714 if (VarT) {
5715 unsigned Offset = this->allocateLocalPrimitive(
5716 VD, *VarT, VarTy.isConstQualified(), VarTy.isVolatileQualified(),
5718
5719 if (!Init || Init->getType()->isVoidType())
5720 return true;
5721
5722 // If this is a toplevel declaration, create a scope for the
5723 // initializer.
5724 if (Toplevel) {
5726 if (!this->visit(Init))
5727 return false;
5728 return this->emitSetLocal(*VarT, Offset, VD) && Scope.destroyLocals();
5729 }
5730 if (!this->visit(Init))
5731 return false;
5732
5733 if (VarTy->isReferenceType()) {
5734 // [C++26][decl.ref]
5735 // The object designated by such a glvalue can be outside its lifetime
5736 // Because a null pointer value or a pointer past the end of an object
5737 // does not point to an object, a reference in a well-defined program
5738 // cannot refer to such things;
5739 assert(classifyPrim(VarTy) == PT_Ptr);
5740 if (!this->emitCheckRefInit(Init))
5741 return false;
5742 }
5743
5744 return this->emitSetLocal(*VarT, Offset, VD);
5745 }
5746 // Local composite variables.
5747 if (UnsignedOrNone Offset =
5748 this->allocateLocal(VD, VarTy, ScopeKind::Block)) {
5749 if (!Init)
5750 return true;
5751
5752 if (!this->emitGetPtrLocal(*Offset, Init))
5753 return false;
5754
5755 return visitInitializerPop(Init);
5756 }
5757 return false;
5758}
5759
5760template <class Emitter>
5762 assert(!canClassify(VD->getType()));
5763
5765 // Create a local variable to use as the instance.
5766 QualType Ty = VD->getType();
5767 Descriptor *D =
5768 P.createDescriptor(VD, Ty.getTypePtr(), /*IsConst=*/Ty.isConstQualified(),
5769 /*IsTemporary=*/false, /*IsMutable=*/false,
5770 /*IsVolatile=*/Ty.isVolatileQualified(), nullptr);
5771 if (!D)
5772 return false;
5773
5774 // FIXME: Would be nice if we didn't allocate the descriptor at all in this
5775 // case.
5776 if (D->hasTrivialDtor())
5777 return true;
5778
5779 Scope::Local Local = this->createLocal(D);
5780 Locals.insert({VD, Local});
5781 VarScope->addForScopeKind(Local, ScopeKind::Block);
5782
5783 if (!this->emitGetPtrLocal(Local.Offset, VD))
5784 return false;
5785
5786 if (!this->visitAPValueInitializer(Value, VD, Ty))
5787 return false;
5788
5789 return this->emitDestructionPop(D, VD);
5790}
5791
5793public:
5795 explicit ParamFinder() {}
5796
5797 bool VisitDeclRefExpr(const DeclRefExpr *E) override {
5798 if (const auto *P = dyn_cast<ParmVarDecl>(E->getDecl()))
5799 FoundParams.insert(P);
5800 return true;
5801 }
5802};
5803
5804/// Evaluate the \p Condition as if it was in the body of \p Callee.
5805/// Specifically, all the parameters of the callee are available to use
5806/// for the condition, and their values are given by \p Args (and \p This).
5807///
5808// Since this is a somewhat niche feature, we're abusing a few other mechanisms
5809// to implement this.
5810//
5811// We don't create an actual function frame but instead register the parameters
5812// as local variables.
5813//
5814// So we evaluate something like:
5815//
5816// bool thisfunc() {
5817// auto Arg0 = Args[0];
5818// ...
5819// return Condition;
5820// }
5821//
5822template <class Emitter>
5825 const Expr *This,
5826 const Expr *Condition) {
5827 // Instead of evaluating all parameters and trying to ignore failure,
5828 // we collect all the parameters used in the condition and only evaluate
5829 // those. Note that we still ignore failure in the loop below because the
5830 // failure might be inconsequential in the end,
5831 // e.g. in the case of `true || x`.
5832 ParamFinder PF;
5834
5835 LocalScope<Emitter> ArgScope(this);
5836 for (const ParmVarDecl *PVD : PF.FoundParams) {
5837 unsigned ParamIndex = 0;
5838 for (const ParmVarDecl *P : Callee->parameters()) {
5839 if (P == PVD)
5840 break;
5841 ++ParamIndex;
5842 }
5843
5844 const Expr *Arg = Args[ParamIndex];
5845 const ParmVarDecl *Param = Callee->getParamDecl(ParamIndex);
5846 if (OptPrimType ParamT = classify(Param->getType())) {
5847 unsigned ArgOffset =
5848 allocateLocalPrimitive(Param, *ParamT, /*IsConst=*/true);
5849 if (!this->visit(Arg))
5850 continue;
5851 if (!this->emitSetLocal(*ParamT, ArgOffset, Arg))
5852 return false;
5853 } else {
5854 UnsignedOrNone ArgOffset = this->allocateLocal(Param, Param->getType());
5855 if (!ArgOffset)
5856 return false;
5857 if (!this->emitGetPtrLocal(*ArgOffset, Arg))
5858 return false;
5859 if (!this->visitInitializerPop(Arg))
5860 continue;
5861 }
5862 }
5863
5864 if (This) {
5865 // We abuse the init stack for this and tell it to use
5866 // either a local variable or another decl for the This pointer.
5867 this->InitStackActive = true;
5868
5869 if (This->getType()->isPointerType()) {
5870 // Nothing to do here, the evaluation will fail if the instance
5871 // pointer is used.
5872 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(This)) {
5873 InitStack.push_back(InitLink::Decl(DRE->getDecl()));
5874 } else {
5875 assert(!canClassify(This->getType()));
5876 UnsignedOrNone ArgOffset = this->allocateLocal(This, This->getType());
5877 if (!ArgOffset)
5878 return false;
5879 if (!this->emitGetPtrLocal(*ArgOffset, This))
5880 return false;
5881 if (!this->visitInitializerPop(This))
5882 return false;
5883 this->InitStack.push_back(InitLink::Temp(*ArgOffset));
5884 }
5885 }
5886
5887 // Destruction of the argument values is part of the callee frame,
5888 // so we simply ignore them here.
5889 this->VarScope = nullptr;
5890
5891 LocalScope<Emitter> RetScope(this);
5892 if (!this->visit(Condition))
5893 return false;
5894 if (!RetScope.destroyLocals())
5895 return false;
5896
5897 // Result of the condition should be on the stack.
5898 return this->emitRet(PT_Bool, Condition);
5899}
5900
5901template <class Emitter>
5903 SourceInfo Info) {
5904 assert(!Val.isIndeterminate() && "Needs to be checked before");
5905 assert(!DiscardResult);
5906 if (Val.isInt())
5907 return this->emitConst(Val.getInt(), ValType, Info);
5908 if (Val.isFloat())
5909 return this->emitFloat(Val.getFloat(), Info);
5910
5911 if (Val.isMemberPointer()) {
5912 if (const ValueDecl *MemberDecl = Val.getMemberPointerDecl()) {
5913 if (!this->emitGetMemberPtr(MemberDecl, Info))
5914 return false;
5915
5916 bool IsDerived = Val.isMemberPointerToDerivedMember();
5917 // Apply the member pointer path.
5918 for (const CXXRecordDecl *PathEntry : Val.getMemberPointerPath()) {
5919 if (!this->emitCopyMemberPtrPath(PathEntry, IsDerived, Info))
5920 return false;
5921 }
5922
5923 return true;
5924 }
5925 return this->emitNullMemberPtr(0, nullptr, Info);
5926 }
5927
5928 if (Val.isLValue()) {
5929 if (Val.isNullPointer())
5930 return this->emitNull(ValType, 0, nullptr, Info);
5931
5933
5934 if (const Expr *BaseExpr = Base.dyn_cast<const Expr *>())
5935 return this->visit(BaseExpr);
5936 if (const auto *VD = Base.dyn_cast<const ValueDecl *>()) {
5937 if (!this->visitDeclRef(VD, Info.asExpr()))
5938 return false;
5939
5940 QualType EntryType = VD->getType();
5941 if (Val.hasLValuePath()) {
5943 for (auto &Entry : Path) {
5944 if (EntryType->isArrayType()) {
5945 uint64_t Index = Entry.getAsArrayIndex();
5946 QualType ElemType =
5947 EntryType->getAsArrayTypeUnsafe()->getElementType();
5948 if (!this->emitConst(Index, PT_Uint64, Info))
5949 return false;
5950 if (!this->emitArrayElemPtrPop(PT_Uint64, Info))
5951 return false;
5952 EntryType = ElemType;
5953 } else {
5954 assert(EntryType->isRecordType());
5955 const Record *EntryRecord = getRecord(EntryType);
5956 if (!EntryRecord)
5957 return false;
5958
5959 const Decl *BaseOrMember = Entry.getAsBaseOrMember().getPointer();
5960 if (const auto *FD = dyn_cast<FieldDecl>(BaseOrMember)) {
5961 unsigned EntryOffset = EntryRecord->getField(FD)->Offset;
5962 if (!this->emitGetPtrFieldPop(EntryOffset, Info))
5963 return false;
5964 EntryType = FD->getType();
5965 } else {
5966 const auto *Base = cast<CXXRecordDecl>(BaseOrMember);
5967 if (const Record::Base *B = EntryRecord->getBaseOrNull(Base)) {
5968 if (!this->emitGetPtrBasePop(B->Offset, /*NullOK=*/false, Info))
5969 return false;
5970 } else {
5971 // Must be a virtual base.
5972 assert(EntryRecord->findVirtualBase(Base));
5973 if (!this->emitGetPtrVirtBasePop(Base, Info))
5974 return false;
5975 }
5976 EntryType = Ctx.getASTContext().getCanonicalTagType(Base);
5977 }
5978 }
5979 }
5980 }
5981
5982 return true;
5983 }
5984 }
5985
5986 return false;
5987}
5988
5989template <class Emitter>
5991 SourceInfo Info, QualType T,
5992 bool IsCompleteClass) {
5993 if (Val.isStruct()) {
5994 const Record *R = this->getRecord(T);
5995 assert(R);
5996
5997 assert(R->getNumBases() == Val.getStructNumBases());
5998 if (IsCompleteClass)
5999 assert(R->getNumVirtualBases() == Val.getStructNumVirtualBases());
6000
6001 for (unsigned I = 0, N = Val.getStructNumBases(); I != N; ++I) {
6002 const APValue &B = Val.getStructBase(I);
6003 if (B.isIndeterminate())
6004 continue;
6005 const Record::Base *RB = R->getBase(I);
6006 QualType BaseType = Ctx.getASTContext().getCanonicalTagType(RB->Decl);
6007
6008 if (!this->emitGetPtrBase(RB->Offset, Info))
6009 return false;
6010 if (!this->visitAPValueInitializer(B, Info, BaseType,
6011 /*IsCompleteClass=*/false))
6012 return false;
6013 if (!this->emitFinishInitPop(Info))
6014 return false;
6015 }
6016
6017 for (unsigned I = 0, N = Val.getStructNumFields(); I != N; ++I) {
6018 const APValue &F = Val.getStructField(I);
6019 if (F.isIndeterminate())
6020 continue;
6021 const Record::Field *RF = R->getField(I);
6022 QualType FieldType = RF->Decl->getType();
6023 // Fields.
6024 if (OptPrimType PT = RF->T) {
6025 if (!this->visitAPValue(F, *PT, Info))
6026 return false;
6027 if (!this->emitInitField(*PT, RF->Offset, Info))
6028 return false;
6029 } else {
6030 if (!this->emitGetPtrField(RF->Offset, Info))
6031 return false;
6032 if (!this->visitAPValueInitializer(F, Info, FieldType))
6033 return false;
6034 if (!this->emitFinishInitPop(Info))
6035 return false;
6036 }
6037 }
6038
6039 // Virtual Bases.
6040 if (IsCompleteClass) {
6041 for (unsigned I = 0, N = Val.getStructNumVirtualBases(); I != N; ++I) {
6042 const APValue &B = Val.getStructVirtualBase(I);
6043 if (B.isIndeterminate())
6044 continue;
6045 const Record::Base *RB = R->getVirtualBase(I);
6046 QualType BaseType = Ctx.getASTContext().getCanonicalTagType(RB->Decl);
6047
6048 if (!this->emitGetPtrVirtBase(cast<CXXRecordDecl>(RB->R->getDecl()),
6049 Info))
6050 return false;
6051 if (!this->visitAPValueInitializer(B, Info, BaseType,
6052 /*IsCompleteClass=*/false))
6053 return false;
6054 if (!this->emitFinishInitPop(Info))
6055 return false;
6056 }
6057 }
6058
6059 return true;
6060 }
6061 if (Val.isUnion()) {
6062 const FieldDecl *UnionField = Val.getUnionField();
6063 if (!UnionField)
6064 return true;
6065 const Record *R = this->getRecord(T);
6066 assert(R);
6067 const APValue &F = Val.getUnionValue();
6068 if (F.isIndeterminate())
6069 return true;
6070 const Record::Field *RF = R->getField(UnionField);
6071 QualType FieldType = RF->Decl->getType();
6072
6073 if (OptPrimType PT = RF->T) {
6074 if (!this->visitAPValue(F, *PT, Info))
6075 return false;
6076 if (RF->isBitField())
6077 return this->emitInitBitFieldActivate(*PT, RF->Offset, RF->bitWidth(),
6078 Info);
6079 return this->emitInitFieldActivate(*PT, RF->Offset, Info);
6080 }
6081
6082 if (!this->emitGetPtrField(RF->Offset, Info))
6083 return false;
6084 if (!this->emitActivate(Info))
6085 return false;
6086 if (!this->visitAPValueInitializer(F, Info, FieldType))
6087 return false;
6088 return this->emitPopPtr(Info);
6089 }
6090 if (Val.isArray()) {
6091 unsigned InitializedElems = Val.getArrayInitializedElts();
6092 const auto *ArrType = T->getAsArrayTypeUnsafe();
6093 QualType ElemType = ArrType->getElementType();
6094 OptPrimType ElemT = classify(ElemType);
6095
6096 for (unsigned A = 0, AN = Val.getArraySize(); A != AN; ++A) {
6097 const APValue &Elem = A >= InitializedElems
6098 ? Val.getArrayFiller()
6099 : Val.getArrayInitializedElt(A);
6100 if (Elem.isIndeterminate())
6101 continue;
6102
6103 if (ElemT) {
6104 if (!this->visitAPValue(Elem, *ElemT, Info))
6105 return false;
6106 if (!this->emitInitElem(*ElemT, A, Info))
6107 return false;
6108 } else {
6109 if (!this->emitConstUint32(A, Info))
6110 return false;
6111 if (!this->emitArrayElemPtrUint32(Info))
6112 return false;
6113 if (!this->visitAPValueInitializer(Elem, Info, ElemType))
6114 return false;
6115 if (!this->emitPopPtr(Info))
6116 return false;
6117 }
6118 }
6119 return true;
6120 }
6121 // TODO: Other types.
6122
6123 return false;
6124}
6125
6126template <class Emitter>
6128 if (P.getGlobal(VD))
6129 return true;
6130
6131 UnsignedOrNone GlobalIndex = P.createGlobal(VD, /*Init=*/nullptr);
6132 if (!GlobalIndex) {
6133 llvm_unreachable("Why didn't that work?");
6134 }
6135
6136 assert(canClassify(VD->getType()) &&
6137 "registerRedecl should only be called with primitive values");
6138
6139 PrimType T = classifyPrim(VD->getType());
6140 if (!visitAPValue(Val, T, VD))
6141 return false;
6142 return this->emitInitGlobal(T, *GlobalIndex, {});
6143}
6144
6145template <class Emitter>
6147 unsigned BuiltinID) {
6148 if (BuiltinID == Builtin::BI__builtin_constant_p) {
6149 // Void argument is always invalid and harder to handle later.
6150 if (E->getArg(0)->getType()->isVoidType()) {
6151 if (DiscardResult)
6152 return true;
6153 return this->emitConst(0, E);
6154 }
6155
6156 if (!this->emitStartSpeculation(E))
6157 return false;
6158 LabelTy EndLabel = this->getLabel();
6159 if (!this->speculate(E, EndLabel))
6160 return false;
6161 if (!this->emitEndSpeculation(E))
6162 return false;
6163 this->fallthrough(EndLabel);
6164 if (DiscardResult)
6165 return this->emitPop(classifyPrim(E), E);
6166 return true;
6167 }
6168
6169 // For these, we're expected to ultimately return an APValue pointing
6170 // to the CallExpr. This is needed to get the correct codegen.
6171 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6172 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString ||
6173 BuiltinID == Builtin::BI__builtin_ptrauth_sign_constant ||
6174 BuiltinID == Builtin::BI__builtin_function_start) {
6175 if (DiscardResult)
6176 return true;
6177 return this->emitDummyPtr(E, E);
6178 }
6179
6181 OptPrimType ReturnT = classify(E);
6182
6183 // Non-primitive return type. Prepare storage.
6184 if (!Initializing && !ReturnT && !ReturnType->isVoidType()) {
6185 UnsignedOrNone LocalIndex = allocateLocal(E);
6186 if (!LocalIndex)
6187 return false;
6188 if (!this->emitGetPtrLocal(*LocalIndex, E))
6189 return false;
6190 }
6191
6192 // Prepare function arguments including special cases.
6193 switch (BuiltinID) {
6194 case Builtin::BI__builtin_object_size:
6195 case Builtin::BI__builtin_dynamic_object_size: {
6196 assert(E->getNumArgs() == 2);
6197 const Expr *Arg0 = E->getArg(0);
6198 if (Arg0->isGLValue()) {
6199 if (!this->visit(Arg0))
6200 return false;
6201
6202 } else {
6204 return false;
6205 }
6206 if (!this->visit(E->getArg(1)))
6207 return false;
6208
6209 } break;
6210 case Builtin::BI__assume:
6211 case Builtin::BI__builtin_assume:
6212 // Argument is not evaluated.
6213 break;
6214 case Builtin::BI__atomic_is_lock_free:
6215 case Builtin::BI__atomic_always_lock_free: {
6216 assert(E->getNumArgs() == 2);
6217 if (!this->visit(E->getArg(0)))
6218 return false;
6219 if (!this->visitAsLValue(E->getArg(1)))
6220 return false;
6221 } break;
6222
6223 default:
6224 if (!Context::isUnevaluatedBuiltin(BuiltinID)) {
6225 // Put arguments on the stack.
6226 for (const auto *Arg : E->arguments()) {
6227 if (!this->visit(Arg))
6228 return false;
6229 }
6230 }
6231 }
6232
6233 if (!this->emitCallBI(E, BuiltinID, E))
6234 return false;
6235
6236 if (DiscardResult && !ReturnType->isVoidType())
6237 return this->emitPop(ReturnT.value_or(PT_Ptr), E);
6238
6239 return true;
6240}
6241
6243 if (!MD || !MD->isDefaulted())
6244 return false;
6246 return false;
6247 return MD->getParent()->isUnion() ||
6249}
6250
6251template <class Emitter>
6253 if (E->containsErrors())
6254 return false;
6255 const FunctionDecl *FuncDecl = E->getDirectCallee();
6256
6257 if (FuncDecl) {
6258 if (unsigned BuiltinID = FuncDecl->getBuiltinID())
6259 return VisitBuiltinCallExpr(E, BuiltinID);
6260
6261 // Calls to replaceable operator new/operator delete.
6263 if (FuncDecl->getDeclName().isAnyOperatorNew())
6264 return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_new);
6265 assert(FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
6266 FuncDecl->getDeclName().getCXXOverloadedOperator() ==
6267 OO_Array_Delete);
6268 return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_delete);
6269 }
6270
6271 // Explicit calls to trivial destructors
6272 if (const auto *DD = dyn_cast<CXXDestructorDecl>(FuncDecl);
6273 DD && DD->isTrivial()) {
6274 const auto *MemberCall = cast<CXXMemberCallExpr>(E);
6275 if (!this->visit(MemberCall->getImplicitObjectArgument()))
6276 return false;
6277 return this->emitCheckDestruction(E) && this->emitEndLifetime(E) &&
6278 this->emitPopPtr(E);
6279 }
6280 }
6281
6282 LocalScope<Emitter> CallScope(this, ScopeKind::Call);
6283 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
6284 bool ActivateLHS = false;
6285
6286 // Emit a special op for trivial copy/move operators.
6287 if (isTrivialMemoryOperation(dyn_cast_if_present<CXXMethodDecl>(FuncDecl))) {
6288 const Function *Func = getFunction(FuncDecl);
6289 if (!Func)
6290 return false;
6291
6292 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
6293 OCE && OCE->isAssignmentOp()) {
6294 const CXXRecordDecl *LHSRecord = Args[0]->getType()->getAsCXXRecordDecl();
6295 ActivateLHS = LHSRecord && LHSRecord->hasTrivialDefaultConstructor();
6296 }
6297 if (const auto *MCE = dyn_cast<CXXMemberCallExpr>(E))
6298 if (!this->visit(MCE->getImplicitObjectArgument()))
6299 return false;
6300
6301 if (!this->visitCallArgs(Args, FuncDecl, /*ActivateLHS=*/ActivateLHS,
6303 return false;
6304
6305 if (!this->emitTrivialCopy(ActivateLHS, Func, E))
6306 return false;
6307
6308 if (!DiscardResult)
6309 return CallScope.destroyLocals();
6310 return this->emitPopPtr(E) && CallScope.destroyLocals();
6311 }
6312
6313 QualType ReturnType = E->getCallReturnType(Ctx.getASTContext());
6315 bool HasRVO = !ReturnType->isVoidType() && !T;
6316
6317 if (HasRVO) {
6318 if (DiscardResult) {
6319 // If we need to discard the return value but the function returns its
6320 // value via an RVO pointer, we need to create one such pointer just
6321 // for this call.
6322 if (UnsignedOrNone LocalIndex = allocateLocal(E)) {
6323 if (!this->emitGetPtrLocal(*LocalIndex, E))
6324 return false;
6325 }
6326 } else {
6327 // We need the result. Prepare a pointer to return or
6328 // dup the current one.
6329 if (!Initializing) {
6330 if (UnsignedOrNone LocalIndex = allocateLocal(E)) {
6331 if (!this->emitGetPtrLocal(*LocalIndex, E))
6332 return false;
6333 }
6334 }
6335 if (!this->emitDupPtr(E))
6336 return false;
6337 }
6338 }
6339
6340 const Expr *ReversedArgs[2];
6341 bool IsAssignmentOperatorCall = false;
6342 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
6343 OCE && OCE->isAssignmentOp()) {
6344 // Just like with regular assignments, we need to special-case assignment
6345 // operators here and evaluate the RHS (the second arg) before the LHS (the
6346 // first arg). We fix this by using a Flip op later.
6347 assert(Args.size() == 2);
6348 const CXXRecordDecl *LHSRecord = Args[0]->getType()->getAsCXXRecordDecl();
6349 ActivateLHS = LHSRecord && LHSRecord->hasTrivialDefaultConstructor();
6350 IsAssignmentOperatorCall = true;
6351 ReversedArgs[0] = Args[1];
6352 ReversedArgs[1] = Args[0];
6353 Args = ReversedArgs;
6354 }
6355
6356 // Calling a static operator will still
6357 // pass the instance, but we don't need it.
6358 // Discard it here.
6359 if (isa<CXXOperatorCallExpr>(E)) {
6360 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl);
6361 MD && MD->isStatic()) {
6362 if (!this->discard(E->getArg(0)))
6363 return false;
6364 // Drop first arg.
6365 Args = Args.drop_front();
6366 }
6367 }
6368
6369 bool Devirtualized = false;
6370 UnsignedOrNone CalleeOffset = std::nullopt;
6371 // Add the (optional, implicit) This pointer.
6372 if (const auto *MC = dyn_cast<CXXMemberCallExpr>(E)) {
6373 if (!FuncDecl && classifyPrim(E->getCallee()) == PT_MemberPtr) {
6374 // If we end up creating a CallPtr op for this, we need the base of the
6375 // member pointer as the instance pointer, and later extract the function
6376 // decl as the function pointer.
6377 const Expr *Callee = E->getCallee();
6378 CalleeOffset =
6379 this->allocateLocalPrimitive(Callee, PT_MemberPtr, /*IsConst=*/true);
6380 if (!this->visit(Callee))
6381 return false;
6382 if (!this->emitSetLocal(PT_MemberPtr, *CalleeOffset, E))
6383 return false;
6384 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
6385 return false;
6386 if (!this->emitGetMemberPtrBase(E))
6387 return false;
6388 } else {
6389 const auto *InstancePtr = MC->getImplicitObjectArgument();
6390 if (isa_and_nonnull<CXXDestructorDecl>(CompilingFunction) ||
6391 isa_and_nonnull<CXXConstructorDecl>(CompilingFunction)) {
6392 const auto *Stripped = stripCheckedDerivedToBaseCasts(InstancePtr);
6393 if (isa<CXXThisExpr>(Stripped)) {
6394 FuncDecl =
6395 cast<CXXMethodDecl>(FuncDecl)->getCorrespondingMethodInClass(
6396 Stripped->getType()->getPointeeType()->getAsCXXRecordDecl());
6397 Devirtualized = true;
6398 if (!this->visit(Stripped))
6399 return false;
6400 } else {
6401 if (!this->visit(InstancePtr))
6402 return false;
6403 }
6404 } else {
6405 if (!this->visit(InstancePtr))
6406 return false;
6407 }
6408 }
6409 } else if (const auto *PD =
6410 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee())) {
6411 if (!this->emitCheckPseudoDtor(E))
6412 return false;
6413 const Expr *Base = PD->getBase();
6414 // E.g. `using T = int; 0.~T();`.
6415 if (OptPrimType BaseT = classify(Base); !BaseT || BaseT != PT_Ptr)
6416 return this->discard(Base);
6417 if (!this->visit(Base))
6418 return false;
6419 return this->emitPseudoDtor(E);
6420 } else if (!FuncDecl) {
6421 const Expr *Callee = E->getCallee();
6422 CalleeOffset =
6423 this->allocateLocalPrimitive(Callee, PT_Ptr, /*IsConst=*/true);
6424 if (!this->visit(Callee))
6425 return false;
6426 if (!this->emitSetLocal(PT_Ptr, *CalleeOffset, E))
6427 return false;
6428 }
6429
6430 if (!this->visitCallArgs(Args, FuncDecl, ActivateLHS,
6432 return false;
6433
6434 // Undo the argument reversal we did earlier.
6435 if (IsAssignmentOperatorCall) {
6436 assert(Args.size() == 2);
6437 PrimType Arg1T = classify(Args[0]).value_or(PT_Ptr);
6438 PrimType Arg2T = classify(Args[1]).value_or(PT_Ptr);
6439 if (!this->emitFlip(Arg2T, Arg1T, E))
6440 return false;
6441 }
6442
6443 if (FuncDecl) {
6444 const Function *Func = getFunction(FuncDecl);
6445 if (!Func)
6446 return false;
6447
6448 // In error cases, the function may be called with fewer arguments than
6449 // parameters.
6450 if (E->getNumArgs() < Func->getNumWrittenParams())
6451 return false;
6452
6453 assert(HasRVO == Func->hasRVO());
6454
6455 bool HasQualifier = false;
6456 if (const auto *ME = dyn_cast<MemberExpr>(E->getCallee()))
6457 HasQualifier = ME->hasQualifier();
6458
6459 bool IsVirtual = false;
6460 if (const auto *MD = dyn_cast<CXXMethodDecl>(FuncDecl))
6461 IsVirtual = !Devirtualized && MD->isVirtual();
6462
6463 // In any case call the function. The return value will end up on the stack
6464 // and if the function has RVO, we already have the pointer on the stack to
6465 // write the result into.
6466 if (IsVirtual && !HasQualifier) {
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
6474 if (!this->emitCallVirt(Func, VarArgSize, E))
6475 return false;
6476 } else if (Func->isVariadic()) {
6477 uint32_t VarArgSize = 0;
6478 unsigned NumParams =
6479 Func->getNumWrittenParams() +
6480 (isa<CXXOperatorCallExpr>(E) && Func->hasImplicitThisPointer());
6481 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
6482 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6483 if (!this->emitCallVar(Func, VarArgSize, E))
6484 return false;
6485 } else {
6486 if (!this->emitCall(Func, 0, E))
6487 return false;
6488 }
6489 } else {
6490 // Indirect call. Visit the callee, which will leave a FunctionPointer on
6491 // the stack. Cleanup of the returned value if necessary will be done after
6492 // the function call completed.
6493
6494 // Sum the size of all args from the call expr.
6495 uint32_t ArgSize = 0;
6496 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
6497 ArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6498
6499 // Get the callee, either from a member pointer or function pointer saved in
6500 // CalleeOffset.
6501 if (isa<CXXMemberCallExpr>(E) && CalleeOffset) {
6502 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
6503 return false;
6504 if (!this->emitGetMemberPtrDecl(E))
6505 return false;
6506 } else {
6507 if (!this->emitGetLocal(PT_Ptr, *CalleeOffset, E))
6508 return false;
6509 }
6510 if (!this->emitCallPtr(ArgSize, E, E))
6511 return false;
6512 }
6513
6514 // Cleanup for discarded return values.
6515 if (DiscardResult && !ReturnType->isVoidType() && T)
6516 return this->emitPop(*T, E) && CallScope.destroyLocals();
6517
6518 return CallScope.destroyLocals();
6519}
6520
6521template <class Emitter>
6523 SourceLocScope<Emitter> SLS(this, E);
6524
6525 return this->delegate(E->getExpr());
6526}
6527
6528template <class Emitter>
6530 SourceLocScope<Emitter> SLS(this, E);
6531
6532 return this->delegate(E->getExpr());
6533}
6534
6535template <class Emitter>
6537 if (DiscardResult)
6538 return true;
6539
6540 return this->emitConstBool(E->getValue(), E);
6541}
6542
6543template <class Emitter>
6545 const CXXNullPtrLiteralExpr *E) {
6546 if (DiscardResult)
6547 return true;
6548
6549 uint64_t Val = Ctx.getASTContext().getTargetNullPointerValue(E->getType());
6550 return this->emitNullPtr(Val, nullptr, E);
6551}
6552
6553template <class Emitter>
6555 if (DiscardResult)
6556 return true;
6557
6558 assert(E->getType()->isIntegerType());
6559
6561 return this->emitZero(T, E);
6562}
6563
6564template <class Emitter>
6566 if (DiscardResult)
6567 return true;
6568
6569 if constexpr (!std::is_same_v<Emitter, EvalEmitter>) {
6570 if (this->LambdaThisCapture.Offset > 0) {
6571 if (this->LambdaThisCapture.IsPtr)
6572 return this->emitGetThisFieldPtr(this->LambdaThisCapture.Offset, E);
6573 return this->emitGetPtrThisField(this->LambdaThisCapture.Offset, E);
6574 }
6575 }
6576
6577 // In some circumstances, the 'this' pointer does not actually refer to the
6578 // instance pointer of the current function frame, but e.g. to the declaration
6579 // currently being initialized. Here we emit the necessary instruction(s) for
6580 // this scenario.
6581 if (!InitStackActive || InitStack.empty())
6582 return this->emitThis(E);
6583
6584 // If our init stack is, for example:
6585 // 0 Stack: 3 (decl)
6586 // 1 Stack: 6 (init list)
6587 // 2 Stack: 1 (field)
6588 // 3 Stack: 6 (init list)
6589 // 4 Stack: 1 (field)
6590 //
6591 // We want to find the LAST element in it that's an init list,
6592 // which is marked with the K_InitList marker. The index right
6593 // before that points to an init list. We need to find the
6594 // elements before the K_InitList element that point to a base
6595 // (e.g. a decl or This), optionally followed by field, elem, etc.
6596 // In the example above, we want to emit elements [0..2].
6597 unsigned StartIndex = 0;
6598 unsigned EndIndex = 0;
6599 // Find the init list.
6600 for (StartIndex = InitStack.size() - 1; StartIndex > 0; --StartIndex) {
6601 if (InitStack[StartIndex].Kind == InitLink::K_DIE) {
6602 EndIndex = StartIndex;
6603 --StartIndex;
6604 break;
6605 }
6606 }
6607
6608 // Walk backwards to find the base.
6609 for (; StartIndex > 0; --StartIndex) {
6610 if (InitStack[StartIndex].Kind == InitLink::K_InitList)
6611 continue;
6612
6613 if (InitStack[StartIndex].Kind != InitLink::K_Field &&
6614 InitStack[StartIndex].Kind != InitLink::K_Elem &&
6615 InitStack[StartIndex].Kind != InitLink::K_Base &&
6616 InitStack[StartIndex].Kind != InitLink::K_DIE)
6617 break;
6618 }
6619
6620 if (StartIndex == 0 && EndIndex == 0)
6621 EndIndex = InitStack.size() - 1;
6622
6623 assert(InitStack[StartIndex].Kind == InitLink::K_Decl ||
6624 InitStack[StartIndex].Kind == InitLink::K_This ||
6625 InitStack[StartIndex].Kind == InitLink::K_Temp ||
6626 InitStack[StartIndex].Kind == InitLink::K_RVO);
6627
6628 // NOTE: This could be StartIndex < EndIndex, but we're also abusing the
6629 // InitStack mechanism in visitWithSubstitutions to have the This pointer
6630 // _just_ be a local variable.
6631 assert(StartIndex <= EndIndex);
6632
6633 // Emit the instructions.
6634 for (unsigned I = StartIndex; I != (EndIndex + 1); ++I) {
6635 if (InitStack[I].Kind == InitLink::K_InitList ||
6636 InitStack[I].Kind == InitLink::K_DIE)
6637 continue;
6638 if (!InitStack[I].template emit<Emitter>(this, E))
6639 return false;
6640 }
6641 return true;
6642}
6643
6644template <class Emitter> bool Compiler<Emitter>::visitStmt(const Stmt *S) {
6645 switch (S->getStmtClass()) {
6646 case Stmt::CompoundStmtClass:
6648 case Stmt::DeclStmtClass:
6649 return visitDeclStmt(cast<DeclStmt>(S), /*EvaluateConditionDecl=*/true);
6650 case Stmt::ReturnStmtClass:
6652 case Stmt::IfStmtClass:
6653 return visitIfStmt(cast<IfStmt>(S));
6654 case Stmt::WhileStmtClass:
6656 case Stmt::DoStmtClass:
6657 return visitDoStmt(cast<DoStmt>(S));
6658 case Stmt::ForStmtClass:
6659 return visitForStmt(cast<ForStmt>(S));
6660 case Stmt::CXXForRangeStmtClass:
6662 case Stmt::BreakStmtClass:
6664 case Stmt::ContinueStmtClass:
6666 case Stmt::SwitchStmtClass:
6668 case Stmt::CaseStmtClass:
6669 return visitCaseStmt(cast<CaseStmt>(S));
6670 case Stmt::DefaultStmtClass:
6672 case Stmt::AttributedStmtClass:
6674 case Stmt::CXXTryStmtClass:
6676 case Stmt::NullStmtClass:
6677 return true;
6678 // Always invalid statements.
6679 case Stmt::GCCAsmStmtClass:
6680 case Stmt::MSAsmStmtClass:
6681 case Stmt::GotoStmtClass:
6682 return this->emitInvalid(S);
6683 case Stmt::LabelStmtClass:
6684 return this->visitStmt(cast<LabelStmt>(S)->getSubStmt());
6685 case Stmt::CXXExpansionStmtInstantiationClass:
6688 default: {
6689 if (const auto *E = dyn_cast<Expr>(S))
6690 return this->discard(E);
6691 return false;
6692 }
6693 }
6694}
6695
6696template <class Emitter>
6699 for (const auto *InnerStmt : S->body())
6700 if (!visitStmt(InnerStmt))
6701 return false;
6702 return Scope.destroyLocals();
6703}
6704
6705template <class Emitter>
6706bool Compiler<Emitter>::maybeEmitDeferredVarInit(const VarDecl *VD) {
6707 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
6708 for (auto *BD : DD->flat_bindings())
6709 if (auto *KD = BD->getHoldingVar();
6710 KD && !this->visitVarDecl(KD, KD->getInit()))
6711 return false;
6712 }
6713 return true;
6714}
6715
6717 assert(FD);
6718 assert(FD->getParent()->isUnion());
6719 const CXXRecordDecl *CXXRD =
6721 return !CXXRD || CXXRD->hasTrivialDefaultConstructor();
6722}
6723
6724template <class Emitter> bool Compiler<Emitter>::refersToUnion(const Expr *E) {
6725 for (;;) {
6726 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
6727 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6728 FD && FD->getParent()->isUnion() && hasTrivialDefaultCtorParent(FD))
6729 return true;
6730 E = ME->getBase();
6731 continue;
6732 }
6733
6734 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6735 E = ASE->getBase()->IgnoreImplicit();
6736 continue;
6737 }
6738
6739 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
6740 ICE && (ICE->getCastKind() == CK_NoOp ||
6741 ICE->getCastKind() == CK_DerivedToBase ||
6742 ICE->getCastKind() == CK_UncheckedDerivedToBase)) {
6743 E = ICE->getSubExpr();
6744 continue;
6745 }
6746
6747 if (const auto *This = dyn_cast<CXXThisExpr>(E)) {
6748 const auto *ThisRecord =
6749 This->getType()->getPointeeType()->getAsRecordDecl();
6750 if (!ThisRecord->isUnion())
6751 return false;
6752 // Otherwise, always activate if we're in the ctor.
6753 if (const auto *Ctor =
6754 dyn_cast_if_present<CXXConstructorDecl>(CompilingFunction))
6755 return Ctor->getParent() == ThisRecord;
6756 return false;
6757 }
6758
6759 break;
6760 }
6761 return false;
6762}
6763
6764template <class Emitter>
6766 bool EvaluateConditionDecl) {
6767 for (const auto *D : DS->decls()) {
6770 continue;
6771
6772 if (const auto *ESD = dyn_cast<CXXExpansionStmtDecl>(D)) {
6773 assert(ESD->getInstantiations() && "not expanded?");
6774 if (!this->visitStmt(ESD->getInstantiations()))
6775 return false;
6776 continue;
6777 }
6778
6779 const auto *VD = dyn_cast<VarDecl>(D);
6780 if (!VD)
6781 return false;
6782 if (!this->visitVarDecl(VD, VD->getInit()))
6783 return false;
6784
6785 // Register decomposition decl holding vars.
6786 if (EvaluateConditionDecl && !this->maybeEmitDeferredVarInit(VD))
6787 return false;
6788 }
6789
6790 return true;
6791}
6792
6793template <class Emitter>
6795 if (this->InStmtExpr)
6796 return this->emitUnsupported(RS);
6797
6798 if (const Expr *RE = RS->getRetValue()) {
6799 LocalScope<Emitter> RetScope(this);
6800 if (ReturnType) {
6801 // Primitive types are simply returned.
6802 if (!this->visit(RE))
6803 return false;
6804 this->emitCleanup();
6805 return this->emitRet(*ReturnType, RS);
6806 }
6807
6808 if (RE->getType()->isVoidType()) {
6809 if (!this->visit(RE))
6810 return false;
6811 } else {
6812 if (RE->containsErrors())
6813 return false;
6814
6816 // RVO - construct the value in the return location.
6817 if (!this->emitRVOPtr(RE))
6818 return false;
6819 if (!this->visitInitializerPop(RE))
6820 return false;
6821
6822 this->emitCleanup();
6823 return this->emitRetVoid(RS);
6824 }
6825 }
6826
6827 // Void return.
6828 this->emitCleanup();
6829 return this->emitRetVoid(RS);
6830}
6831
6832template <class Emitter> bool Compiler<Emitter>::visitIfStmt(const IfStmt *IS) {
6833 LocalScope<Emitter> IfScope(this);
6834
6835 auto visitChildStmt = [&](const Stmt *S) -> bool {
6836 LocalScope<Emitter> SScope(this);
6837 if (!visitStmt(S))
6838 return false;
6839 return SScope.destroyLocals();
6840 };
6841
6842 if (auto *CondInit = IS->getInit()) {
6843 if (!visitStmt(CondInit))
6844 return false;
6845 }
6846
6847 if (const DeclStmt *CondDecl = IS->getConditionVariableDeclStmt()) {
6848 if (!visitDeclStmt(CondDecl))
6849 return false;
6850 }
6851
6852 // Save ourselves compiling some code and the jumps, etc. if the condition is
6853 // stataically known to be either true or false. We could look at more cases
6854 // here, but I think all the ones that actually happen are using a
6855 // ConstantExpr.
6856 if (std::optional<bool> BoolValue = getBoolValue(IS->getCond())) {
6857 if (*BoolValue)
6858 return visitChildStmt(IS->getThen());
6859 if (const Stmt *Else = IS->getElse())
6860 return visitChildStmt(Else);
6861 return true;
6862 }
6863
6864 // Otherwise, compile the condition.
6865 if (IS->isNonNegatedConsteval()) {
6866 if (!this->emitIsConstantContext(IS))
6867 return false;
6868 } else if (IS->isNegatedConsteval()) {
6869 if (!this->emitIsConstantContext(IS))
6870 return false;
6871 if (!this->emitInv(IS))
6872 return false;
6873 } else {
6875 if (!this->visitBool(IS->getCond()))
6876 return false;
6877 if (!CondScope.destroyLocals())
6878 return false;
6879 }
6880
6881 if (!this->maybeEmitDeferredVarInit(IS->getConditionVariable()))
6882 return false;
6883
6884 if (const Stmt *Else = IS->getElse()) {
6885 LabelTy LabelElse = this->getLabel();
6886 LabelTy LabelEnd = this->getLabel();
6887 if (!this->jumpFalse(LabelElse, IS))
6888 return false;
6889 if (!visitChildStmt(IS->getThen()))
6890 return false;
6891 if (!this->jump(LabelEnd, IS))
6892 return false;
6893 this->emitLabel(LabelElse);
6894 if (!visitChildStmt(Else))
6895 return false;
6896 this->emitLabel(LabelEnd);
6897 } else {
6898 LabelTy LabelEnd = this->getLabel();
6899 if (!this->jumpFalse(LabelEnd, IS))
6900 return false;
6901 if (!visitChildStmt(IS->getThen()))
6902 return false;
6903 this->emitLabel(LabelEnd);
6904 }
6905
6906 if (!IfScope.destroyLocals())
6907 return false;
6908
6909 return true;
6910}
6911
6912template <class Emitter>
6914 const Expr *Cond = S->getCond();
6915 const Stmt *Body = S->getBody();
6916
6917 LabelTy CondLabel = this->getLabel(); // Label before the condition.
6918 LabelTy EndLabel = this->getLabel(); // Label after the loop.
6919 LocalScope<Emitter> WholeLoopScope(this);
6920 LoopScope<Emitter> LS(this, S, EndLabel, CondLabel);
6921
6922 this->fallthrough(CondLabel);
6923 this->emitLabel(CondLabel);
6924
6925 // Start of the loop body {
6926 LocalScope<Emitter> CondScope(this);
6927
6928 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) {
6929 if (!visitDeclStmt(CondDecl))
6930 return false;
6931 }
6932
6933 if (!this->visitBool(Cond))
6934 return false;
6935
6936 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
6937 return false;
6938
6939 if (!this->jumpFalse(EndLabel, S))
6940 return false;
6941
6942 if (!this->visitStmt(Body))
6943 return false;
6944
6945 if (!CondScope.destroyLocals())
6946 return false;
6947 // } End of loop body.
6948
6949 if (!this->jump(CondLabel, S))
6950 return false;
6951 this->fallthrough(EndLabel);
6952 this->emitLabel(EndLabel);
6953
6954 return CondScope.destroyLocals() && WholeLoopScope.destroyLocals();
6955}
6956
6957template <class Emitter> bool Compiler<Emitter>::visitDoStmt(const DoStmt *S) {
6958 const Expr *Cond = S->getCond();
6959 const Stmt *Body = S->getBody();
6960
6961 LabelTy StartLabel = this->getLabel();
6962 LabelTy EndLabel = this->getLabel();
6963 LabelTy CondLabel = this->getLabel();
6964 LocalScope<Emitter> WholeLoopScope(this);
6965 LoopScope<Emitter> LS(this, S, EndLabel, CondLabel);
6966
6967 this->fallthrough(StartLabel);
6968 this->emitLabel(StartLabel);
6969
6970 {
6971 LocalScope<Emitter> CondScope(this);
6972 if (!this->visitStmt(Body))
6973 return false;
6974 this->fallthrough(CondLabel);
6975 this->emitLabel(CondLabel);
6976 if (!this->visitBool(Cond))
6977 return false;
6978
6979 if (!CondScope.destroyLocals())
6980 return false;
6981 }
6982 if (!this->jumpTrue(StartLabel, S))
6983 return false;
6984
6985 this->fallthrough(EndLabel);
6986 this->emitLabel(EndLabel);
6987 return WholeLoopScope.destroyLocals();
6988}
6989
6990template <class Emitter>
6992 // for (Init; Cond; Inc) { Body }
6993 const Stmt *Init = S->getInit();
6994 const Expr *Cond = S->getCond();
6995 const Expr *Inc = S->getInc();
6996 const Stmt *Body = S->getBody();
6997
6998 LabelTy EndLabel = this->getLabel();
6999 LabelTy CondLabel = this->getLabel();
7000 LabelTy IncLabel = this->getLabel();
7001
7002 LocalScope<Emitter> WholeLoopScope(this);
7003 if (Init && !this->visitStmt(Init))
7004 return false;
7005
7006 // Start of the loop body {
7007 this->fallthrough(CondLabel);
7008 this->emitLabel(CondLabel);
7009
7010 LocalScope<Emitter> CondScope(this);
7011 LoopScope<Emitter> LS(this, S, EndLabel, IncLabel);
7012 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) {
7013 if (!visitDeclStmt(CondDecl))
7014 return false;
7015 }
7016
7017 if (Cond) {
7018 if (!this->visitBool(Cond))
7019 return false;
7020 if (!this->jumpFalse(EndLabel, S))
7021 return false;
7022 }
7023 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
7024 return false;
7025
7026 if (Body && !this->visitStmt(Body))
7027 return false;
7028
7029 this->fallthrough(IncLabel);
7030 this->emitLabel(IncLabel);
7031 if (Inc && !this->discard(Inc))
7032 return false;
7033
7034 if (!CondScope.destroyLocals())
7035 return false;
7036 if (!this->jump(CondLabel, S))
7037 return false;
7038 // } End of loop body.
7039
7040 this->emitLabel(EndLabel);
7041 // If we jumped out of the loop above, we still need to clean up the condition
7042 // scope.
7043 return CondScope.destroyLocals() && WholeLoopScope.destroyLocals();
7044}
7045
7046template <class Emitter>
7048 const Stmt *Init = S->getInit();
7049 const Expr *Cond = S->getCond();
7050 const Expr *Inc = S->getInc();
7051 const Stmt *Body = S->getBody();
7052 const Stmt *BeginStmt = S->getBeginStmt();
7053 const Stmt *RangeStmt = S->getRangeStmt();
7054 const Stmt *EndStmt = S->getEndStmt();
7055
7056 LabelTy EndLabel = this->getLabel();
7057 LabelTy CondLabel = this->getLabel();
7058 LabelTy IncLabel = this->getLabel();
7059 LocalScope<Emitter> WholeLoopScope(this);
7060 LoopScope<Emitter> LS(this, S, EndLabel, IncLabel);
7061
7062 // Emit declarations needed in the loop.
7063 if (Init && !this->visitStmt(Init))
7064 return false;
7065 if (!this->visitStmt(RangeStmt))
7066 return false;
7067 if (!this->visitStmt(BeginStmt))
7068 return false;
7069 if (!this->visitStmt(EndStmt))
7070 return false;
7071
7072 LocalScope<Emitter> CondScope(this);
7073 // Now the condition as well as the loop variable assignment.
7074 this->fallthrough(CondLabel);
7075 this->emitLabel(CondLabel);
7076 if (!this->visitBool(Cond))
7077 return false;
7078 if (!this->jumpFalse(EndLabel, S))
7079 return false;
7080
7081 if (!this->visitDeclStmt(S->getLoopVarStmt(), /*EvaluateConditionDecl=*/true))
7082 return false;
7083
7084 // Body.
7085 {
7086 if (!this->visitStmt(Body))
7087 return false;
7088
7089 this->fallthrough(IncLabel);
7090 this->emitLabel(IncLabel);
7091 if (!this->discard(Inc))
7092 return false;
7093 }
7094
7095 if (!CondScope.destroyLocals())
7096 return false;
7097 if (!this->jump(CondLabel, S))
7098 return false;
7099
7100 this->fallthrough(EndLabel);
7101 this->emitLabel(EndLabel);
7102 return WholeLoopScope.destroyLocals();
7103}
7104
7105template <class Emitter>
7107 if (LabelInfoStack.empty())
7108 return false;
7109
7110 OptLabelTy TargetLabel = std::nullopt;
7111 const Stmt *TargetLoop = S->getNamedLoopOrSwitch();
7112 const VariableScope<Emitter> *BreakScope = nullptr;
7113
7114 if (!TargetLoop) {
7115 for (const auto &LI : llvm::reverse(LabelInfoStack)) {
7116 if (LI.BreakLabel) {
7117 TargetLabel = *LI.BreakLabel;
7118 BreakScope = LI.BreakOrContinueScope;
7119 break;
7120 }
7121 }
7122 } else {
7123 for (const auto &LI : LabelInfoStack) {
7124 if (LI.Name == TargetLoop) {
7125 TargetLabel = *LI.BreakLabel;
7126 BreakScope = LI.BreakOrContinueScope;
7127 break;
7128 }
7129 }
7130 }
7131
7132 // Faulty break statement (e.g. label redefined or named loops disabled).
7133 if (!TargetLabel)
7134 return false;
7135
7136 for (VariableScope<Emitter> *C = this->VarScope; C != BreakScope;
7137 C = C->getParent()) {
7138 if (!C->destroyLocals())
7139 return false;
7140 }
7141
7142 return this->jump(*TargetLabel, S);
7143}
7144
7145template <class Emitter>
7147 if (LabelInfoStack.empty())
7148 return false;
7149
7150 OptLabelTy TargetLabel = std::nullopt;
7151 const Stmt *TargetLoop = S->getNamedLoopOrSwitch();
7152 const VariableScope<Emitter> *ContinueScope = nullptr;
7153
7154 if (!TargetLoop) {
7155 for (const auto &LI : llvm::reverse(LabelInfoStack)) {
7156 if (LI.ContinueLabel) {
7157 TargetLabel = *LI.ContinueLabel;
7158 ContinueScope = LI.BreakOrContinueScope;
7159 break;
7160 }
7161 }
7162 } else {
7163 for (auto LI : LabelInfoStack) {
7164 if (LI.Name == TargetLoop) {
7165 TargetLabel = *LI.ContinueLabel;
7166 ContinueScope = LI.BreakOrContinueScope;
7167 break;
7168 }
7169 }
7170 }
7171
7172 if (!TargetLabel)
7173 return false;
7174
7175 for (VariableScope<Emitter> *C = VarScope; C != ContinueScope;
7176 C = C->getParent()) {
7177 if (!C->destroyLocals())
7178 return false;
7179 }
7180
7181 return this->jump(*TargetLabel, S);
7182}
7183
7184template <class Emitter>
7186 const Expr *Cond = S->getCond();
7187 if (Cond->containsErrors())
7188 return false;
7189
7190 PrimType CondT = this->classifyPrim(Cond->getType());
7191 LocalScope<Emitter> LS(this);
7192 llvm::SaveAndRestore StmtExprSAR(this->SwitchInStmtExpr, this->InStmtExpr);
7193
7194 LabelTy EndLabel = this->getLabel();
7195 UnsignedOrNone DefaultLabel = std::nullopt;
7196 unsigned CondVar =
7197 this->allocateLocalPrimitive(Cond, CondT, /*IsConst=*/true);
7198
7199 if (const auto *CondInit = S->getInit())
7200 if (!visitStmt(CondInit))
7201 return false;
7202
7203 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
7204 if (!visitDeclStmt(CondDecl))
7205 return false;
7206
7207 // Initialize condition variable.
7208 if (!this->visit(Cond))
7209 return false;
7210 if (!this->emitSetLocal(CondT, CondVar, S))
7211 return false;
7212
7213 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
7214 return false;
7215
7217 // Create labels and comparison ops for all case statements.
7218 for (const SwitchCase *SC = S->getSwitchCaseList(); SC;
7219 SC = SC->getNextSwitchCase()) {
7220 if (const auto *CS = dyn_cast<CaseStmt>(SC)) {
7221 CaseLabels[SC] = this->getLabel();
7222
7223 if (CS->caseStmtIsGNURange()) {
7224 LabelTy EndOfRangeCheck = this->getLabel();
7225 const Expr *Low = CS->getLHS();
7226 const Expr *High = CS->getRHS();
7227 if (Low->isValueDependent() || High->isValueDependent())
7228 return false;
7229
7230 if (!this->emitGetLocal(CondT, CondVar, CS))
7231 return false;
7232 if (!this->visit(Low))
7233 return false;
7234 PrimType LT = this->classifyPrim(Low->getType());
7235 if (!this->emitGE(LT, S))
7236 return false;
7237 if (!this->jumpFalse(EndOfRangeCheck, S))
7238 return false;
7239
7240 if (!this->emitGetLocal(CondT, CondVar, CS))
7241 return false;
7242 if (!this->visit(High))
7243 return false;
7244 PrimType HT = this->classifyPrim(High->getType());
7245 if (!this->emitLE(HT, S))
7246 return false;
7247 if (!this->jumpTrue(CaseLabels[CS], S))
7248 return false;
7249 this->emitLabel(EndOfRangeCheck);
7250 continue;
7251 }
7252
7253 const Expr *Value = CS->getLHS();
7254 if (Value->isValueDependent())
7255 return false;
7256 PrimType ValueT = this->classifyPrim(Value->getType());
7257
7258 // Compare the case statement's value to the switch condition.
7259 if (!this->emitGetLocal(CondT, CondVar, CS))
7260 return false;
7261 if (!this->visit(Value))
7262 return false;
7263
7264 // Compare and jump to the case label.
7265 if (!this->emitEQ(ValueT, S))
7266 return false;
7267 if (!this->jumpTrue(CaseLabels[CS], S))
7268 return false;
7269 } else {
7270 assert(!DefaultLabel);
7271 DefaultLabel = this->getLabel();
7272 }
7273 }
7274
7275 // If none of the conditions above were true, fall through to the default
7276 // statement or jump after the switch statement.
7277 if (DefaultLabel) {
7278 if (!this->jump(*DefaultLabel, S))
7279 return false;
7280 } else {
7281 if (!this->jump(EndLabel, S))
7282 return false;
7283 }
7284
7285 SwitchScope<Emitter> SS(this, S, std::move(CaseLabels), EndLabel,
7286 DefaultLabel);
7287 if (!this->visitStmt(S->getBody()))
7288 return false;
7289 this->fallthrough(EndLabel);
7290 this->emitLabel(EndLabel);
7291
7292 return LS.destroyLocals();
7293}
7294
7295template <class Emitter>
7297 this->fallthrough(CaseLabels[S]);
7298 this->emitLabel(CaseLabels[S]);
7299
7300 // We can't jump from an outer switch statement to a case label
7301 // that's inside a StmtExpr.
7302 if (this->InStmtExpr && !this->SwitchInStmtExpr)
7303 return this->emitUnsupported(S);
7304
7305 return this->visitStmt(S->getSubStmt());
7306}
7307
7308template <class Emitter>
7310 if (LabelInfoStack.empty())
7311 return false;
7312
7313 LabelTy DefaultLabel;
7314 for (const LabelInfo &LI : llvm::reverse(LabelInfoStack)) {
7315 if (LI.DefaultLabel) {
7316 DefaultLabel = *LI.DefaultLabel;
7317 break;
7318 }
7319 }
7320
7321 this->emitLabel(DefaultLabel);
7322 return this->visitStmt(S->getSubStmt());
7323}
7324
7325template <class Emitter>
7327 const Stmt *SubStmt = S->getSubStmt();
7328
7329 bool IsMSVCConstexprAttr = isa<ReturnStmt>(SubStmt) &&
7331
7332 if (IsMSVCConstexprAttr && !this->emitPushMSVCCE(S))
7333 return false;
7334
7335 if (this->Ctx.getLangOpts().CXXAssumptions &&
7336 !this->Ctx.getLangOpts().MSVCCompat) {
7337 for (const Attr *A : S->getAttrs()) {
7338 auto *AA = dyn_cast<CXXAssumeAttr>(A);
7339 if (!AA)
7340 continue;
7341
7342 assert(isa<NullStmt>(SubStmt));
7343
7344 const Expr *Assumption = AA->getAssumption();
7345 if (Assumption->isValueDependent())
7346 return false;
7347
7348 if (Assumption->HasSideEffects(this->Ctx.getASTContext()))
7349 continue;
7350
7351 // Evaluate assumption.
7352 if (!this->visitBool(Assumption))
7353 return false;
7354
7355 if (!this->emitAssume(Assumption))
7356 return false;
7357 }
7358 }
7359
7360 // Ignore other attributes.
7361 if (!this->visitStmt(SubStmt))
7362 return false;
7363
7364 if (IsMSVCConstexprAttr)
7365 return this->emitPopMSVCCE(S);
7366 return true;
7367}
7368
7369template <class Emitter>
7371 // Ignore all handlers.
7372 return this->visitStmt(S->getTryBlock());
7373}
7374
7375/// template for (auto x : {1, 2}) {}
7376///
7377/// This is not a loop from an AST perspective at all since it has already
7378/// been instantiated to a list of compound statements.
7379///
7380/// Since we can have control flow in those compound statements, we need to
7381/// handle it mostly like a loop though.
7382template <class Emitter>
7385 LocalScope<Emitter> WholeLoopScope(this, ScopeKind::Block);
7386
7387 for (const Stmt *PreambleStmt : S->getPreambleStmts()) {
7388 if (!this->visitDeclStmt(cast<DeclStmt>(PreambleStmt), true))
7389 return false;
7390 }
7391
7392 LabelTy EndLabel = this->getLabel();
7393 for (const Stmt *Instantiation : S->getInstantiations()) {
7394 LabelTy ContinueLabel = this->getLabel();
7395 LoopScope<Emitter> LS(this, S, EndLabel, ContinueLabel);
7396
7397 if (!this->visitStmt(Instantiation))
7398 return false;
7399 this->emitLabel(ContinueLabel);
7400 }
7401
7402 this->emitLabel(EndLabel);
7403
7404 return WholeLoopScope.destroyLocals();
7405}
7406
7407template <class Emitter>
7408bool Compiler<Emitter>::emitLambdaStaticInvokerBody(const CXXMethodDecl *MD) {
7409 assert(MD->isLambdaStaticInvoker());
7410 assert(MD->hasBody());
7411 assert(cast<CompoundStmt>(MD->getBody())->body_empty());
7412
7413 const CXXRecordDecl *ClosureClass = MD->getParent();
7414 const FunctionDecl *LambdaCallOp;
7415 assert(ClosureClass->captures().empty());
7416 if (ClosureClass->isGenericLambda()) {
7417 LambdaCallOp = ClosureClass->getLambdaCallOperator();
7418 assert(MD->isFunctionTemplateSpecialization() &&
7419 "A generic lambda's static-invoker function must be a "
7420 "template specialization");
7422 FunctionTemplateDecl *CallOpTemplate =
7423 LambdaCallOp->getDescribedFunctionTemplate();
7424 llvm::FoldingSetInsertToken InsertToken;
7425 const FunctionDecl *CorrespondingCallOpSpecialization =
7426 CallOpTemplate->findSpecialization(TAL->asArray(), InsertToken);
7427 assert(CorrespondingCallOpSpecialization);
7428 LambdaCallOp = CorrespondingCallOpSpecialization;
7429 } else {
7430 LambdaCallOp = ClosureClass->getLambdaCallOperator();
7431 }
7432 assert(ClosureClass->captures().empty());
7433 const Function *Func = this->getFunction(LambdaCallOp);
7434 if (!Func)
7435 return false;
7436 assert(Func->hasThisPointer());
7437 assert(Func->getNumParams() == (MD->getNumParams() + 1 + Func->hasRVO()));
7438
7439 if (Func->hasRVO()) {
7440 if (!this->emitRVOPtr(MD))
7441 return false;
7442 }
7443
7444 // The lambda call operator needs an instance pointer, but we don't have
7445 // one here, and we don't need one either because the lambda cannot have
7446 // any captures, as verified above. Emit a null pointer. This is then
7447 // special-cased when interpreting to not emit any misleading diagnostics.
7448 if (!this->emitNullPtr(0, nullptr, MD))
7449 return false;
7450
7451 // Forward all arguments from the static invoker to the lambda call operator.
7452 for (const ParmVarDecl *PVD : MD->parameters()) {
7453 auto It = this->Params.find(PVD);
7454 assert(It != this->Params.end());
7455
7456 // We do the lvalue-to-rvalue conversion manually here, so no need
7457 // to care about references.
7458 PrimType ParamType = this->classify(PVD->getType()).value_or(PT_Ptr);
7459 if (!this->emitGetParam(ParamType, It->second.Index, MD))
7460 return false;
7461 }
7462
7463 if (!this->emitCall(Func, 0, LambdaCallOp))
7464 return false;
7465
7466 this->emitCleanup();
7467 if (ReturnType)
7468 return this->emitRet(*ReturnType, MD);
7469
7470 // Nothing to do, since we emitted the RVO pointer above.
7471 return this->emitRetVoid(MD);
7472}
7473
7474template <class Emitter>
7475bool Compiler<Emitter>::checkLiteralType(const Expr *E) {
7476 if (Ctx.getLangOpts().CPlusPlus23)
7477 return true;
7478
7479 if (!E->isPRValue() || E->getType()->isLiteralType(Ctx.getASTContext()))
7480 return true;
7481
7482 return this->emitCheckLiteralType(E->getType().getTypePtr(), E);
7483}
7484
7486 const Expr *InitExpr = Init->getInit();
7487
7488 if (!Init->isWritten() && !Init->isInClassMemberInitializer() &&
7489 !isa<CXXConstructExpr>(InitExpr))
7490 return true;
7491
7492 if (const auto *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
7493 const CXXConstructorDecl *Ctor = CE->getConstructor();
7494 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
7495 Ctor->isTrivial())
7496 return true;
7497 }
7498
7499 return false;
7500}
7501
7502template <class Emitter>
7503bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
7504 assert(!ReturnType);
7505
7506 // Only start the lifetime of the instance pointer.
7507 if (!this->emitStartThisLifetime1(Ctor))
7508 return false;
7509
7510 auto emitFieldInitializer = [&](const Record::Field *F, unsigned FieldOffset,
7511 const Expr *InitExpr,
7512 bool Activate = false) -> bool {
7513 // We don't know what to do with these, so just return false.
7514 if (InitExpr->getType().isNull())
7515 return false;
7516
7517 if (OptPrimType T = this->classify(InitExpr)) {
7518 if (Activate && !this->emitActivateThisField(FieldOffset, InitExpr))
7519 return false;
7520
7521 if (!this->visit(InitExpr))
7522 return false;
7523
7524 if (F->isBitField())
7525 return this->emitInitThisBitField(*T, FieldOffset, F->bitWidth(),
7526 InitExpr);
7527 return this->emitInitThisField(*T, FieldOffset, InitExpr);
7528 }
7529 // Non-primitive case. Get a pointer to the field-to-initialize
7530 // on the stack and call visitInitialzer() for it.
7531 InitLinkScope<Emitter> FieldScope(this, InitLink::Field(F->Offset));
7532 if (!this->emitGetPtrThisField(FieldOffset, InitExpr))
7533 return false;
7534
7535 if (Activate && !this->emitActivate(InitExpr))
7536 return false;
7537
7538 return this->visitInitializerPop(InitExpr);
7539 };
7540
7541 const RecordDecl *RD = Ctor->getParent();
7542 const Record *R = this->getRecord(RD);
7543 if (!R)
7544 return false;
7545 bool IsUnion = R->isUnion();
7546
7547 // Default union copy and move ctors are special.
7548 if (IsUnion && Ctor->isCopyOrMoveConstructor() && Ctor->isDefaulted()) {
7550
7551 // No special case for NumFields == 0 here, so the Memcpy op
7552 // below also does its checks in those cases.
7553
7554 assert(cast<CompoundStmt>(Ctor->getBody())->body_empty());
7555 if (!this->emitThis(Ctor))
7556 return false;
7557
7558 if (!this->emitGetParam(PT_Ptr, /*ParamIndex=*/0, Ctor))
7559 return false;
7560
7561 return this->emitMemcpy(Ctor) && this->emitPopPtr(Ctor) &&
7562 this->emitRetVoid(Ctor);
7563 }
7564
7565 unsigned FieldInits = 0;
7567 // First, initialize virtual bases if the records has them.
7568 if (R->getNumVirtualBases() > 0) {
7569 if (!this->emitThis(Ctor))
7570 return false;
7571 LabelTy AfterVirtBasesLabel = this->getLabel();
7572
7573 // If the instance pointer is a base class, skip the virtual bases.
7574 if (!this->emitIsBaseClass({}))
7575 return false;
7576 if (!this->jumpTrue(AfterVirtBasesLabel, {}))
7577 return false;
7578
7579 for (const auto *Init : Ctor->inits()) {
7580 if (const Type *Base = Init->getBaseClass();
7581 Base && Init->isBaseVirtual()) {
7582 const auto *BaseDecl = Base->getAsCXXRecordDecl();
7583 assert(BaseDecl);
7584 assert(R->findVirtualBase(BaseDecl));
7585 if (!this->emitGetPtrThisVirtBase(BaseDecl, Ctor))
7586 return false;
7587 if (!this->visitInitializerPop(Init->getInit()))
7588 return false;
7589 }
7590 }
7591
7592 this->fallthrough(AfterVirtBasesLabel);
7593 this->emitLabel(AfterVirtBasesLabel);
7594
7595 if (!this->emitPopPtr(Ctor))
7596 return false;
7597 }
7598
7599 for (const auto *Init : Ctor->inits()) {
7600 // Scope needed for the initializers.
7601 LocalScope<Emitter> Scope(this, ScopeKind::FullExpression);
7602
7603 const Expr *InitExpr = Init->getInit();
7604 if (const FieldDecl *Member = Init->getMember()) {
7605 const Record::Field *F = R->getField(Member);
7606
7609 if (!emitFieldInitializer(F, F->Offset, InitExpr, IsUnion))
7610 return false;
7611 ++FieldInits;
7612 } else if (const Type *Base = Init->getBaseClass()) {
7613 const auto *BaseDecl = Base->getAsCXXRecordDecl();
7614 assert(BaseDecl);
7615
7616 if (Init->isBaseVirtual()) {
7617 // See above.
7618 continue;
7619 } else {
7620 // Base class initializer.
7621 // Get This Base and call initializer on it.
7622 const Record::Base *B = R->getBase(BaseDecl);
7623 assert(B);
7624 if (!this->emitGetPtrThisBase(B->Offset, InitExpr))
7625 return false;
7626 }
7627
7628 if (!this->visitInitializerPop(InitExpr))
7629 return false;
7630 } else if (const IndirectFieldDecl *IFD = Init->getIndirectMember()) {
7633 unsigned ChainSize = IFD->getChainingSize();
7634 assert(ChainSize >= 2);
7635
7636 unsigned NestedFieldOffset = 0;
7637 const Record::Field *NestedField = nullptr;
7638 for (unsigned I = 0; I != ChainSize; ++I) {
7639 const auto *FD = cast<FieldDecl>(IFD->chain()[I]);
7640 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
7641 assert(FieldRecord);
7642
7643 NestedField = FieldRecord->getField(FD);
7644 assert(NestedField);
7645 IsUnion = IsUnion || FieldRecord->isUnion();
7646
7647 NestedFieldOffset += NestedField->Offset;
7648
7649 // Add a new InitChainLink for the record, but not for the final field.
7650 if (I != ChainSize - 1)
7651 InitStack.push_back(InitLink::Field(NestedField->Offset));
7652 }
7653 assert(NestedField);
7654
7656 if (!emitFieldInitializer(NestedField, NestedFieldOffset, InitExpr,
7657 IsUnion))
7658 return false;
7659
7660 // Mark all chain links as initialized.
7661 unsigned InitFieldOffset = 0;
7662 for (const NamedDecl *ND : IFD->chain().drop_back()) {
7663 const auto *FD = cast<FieldDecl>(ND);
7664 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
7665 assert(FieldRecord);
7666 NestedField = FieldRecord->getField(FD);
7667 InitFieldOffset += NestedField->Offset;
7668 assert(NestedField);
7669 if (!this->emitGetPtrThisField(InitFieldOffset, InitExpr))
7670 return false;
7671 if (!this->emitFinishInitPop(InitExpr))
7672 return false;
7673 }
7674
7675 InitStack.pop_back_n(ChainSize - 1);
7676
7677 } else {
7678 assert(Init->isDelegatingInitializer());
7679 if (!this->emitThis(InitExpr))
7680 return false;
7681 if (!this->visitInitializerPop(Init->getInit()))
7682 return false;
7683 }
7684
7685 if (!Scope.destroyLocals())
7686 return false;
7687 }
7688
7689 if (FieldInits != R->getNumFields()) {
7690 assert(FieldInits < R->getNumFields());
7691 // Start the lifetime of all members.
7692 if (!this->emitStartThisLifetime(Ctor))
7693 return false;
7694 }
7695
7696 if (const Stmt *Body = Ctor->getBody()) {
7697 // Only emit the CtorCheck op for non-empty CompoundStmt bodies.
7698 // For non-CompoundStmts, always assume they are non-empty and emit it.
7699 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
7700 if (!CS->body_empty() && !this->emitCtorCheck(SourceInfo{}))
7701 return false;
7702 } else {
7703 if (!this->emitCtorCheck(SourceInfo{}))
7704 return false;
7705 }
7706
7707 if (!visitStmt(Body))
7708 return false;
7709 }
7710
7711 return this->emitRetVoid(SourceInfo{});
7712}
7713
7714template <class Emitter>
7715bool Compiler<Emitter>::compileDestructor(const CXXDestructorDecl *Dtor) {
7716 const RecordDecl *RD = Dtor->getParent();
7717 const Record *R = this->getRecord(RD);
7718 if (!R)
7719 return false;
7720
7721 if (!Dtor->isTrivial() && Dtor->getBody()) {
7722 if (!this->visitStmt(Dtor->getBody()))
7723 return false;
7724 }
7725
7726 if (!this->emitThis(Dtor))
7727 return false;
7728
7729 if (!this->emitCheckDestruction(Dtor))
7730 return false;
7731
7732 assert(R);
7733 if (!R->isUnion()) {
7734
7736 // First, destroy all fields.
7737 for (const Record::Field &Field : llvm::reverse(R->fields())) {
7738 const Descriptor *D = Field.Desc;
7739 if (D->hasTrivialDtor())
7740 continue;
7741 if (!this->emitGetPtrField(Field.Offset, SourceInfo{}))
7742 return false;
7743 if (!this->emitDestructionPop(D, SourceInfo{}))
7744 return false;
7745 }
7746 }
7747
7748 for (const Record::Base &Base : llvm::reverse(R->bases())) {
7749 if (Base.R->hasTrivialDtor())
7750 continue;
7751 if (!this->emitGetPtrBase(Base.Offset, SourceInfo{}))
7752 return false;
7753 if (!this->emitRecordDestructionPop(Base.R, {}))
7754 return false;
7755 }
7756
7757 if (R->getNumVirtualBases() > 0) {
7758 LabelTy EndLabel = this->getLabel();
7759 // If this is a base class, skip the virtual bases.
7760 if (!this->emitIsBaseClass({}))
7761 return false;
7762 if (!this->jumpTrue(EndLabel, {}))
7763 return false;
7764
7765 for (const Record::Base &Base : llvm::reverse(R->virtual_bases())) {
7766 if (Base.R->hasTrivialDtor())
7767 continue;
7768 if (!this->emitGetPtrVirtBase(cast<CXXRecordDecl>(Base.R->getDecl()),
7769 SourceInfo{}))
7770 return false;
7771 if (!this->emitRecordDestructionPop(Base.R, {}))
7772 return false;
7773 }
7774
7775 this->fallthrough(EndLabel);
7776 this->emitLabel(EndLabel);
7777 }
7778
7779 if (!this->emitMarkDestroyed(Dtor))
7780 return false;
7781
7782 return this->emitPopPtr(Dtor) && this->emitRetVoid(Dtor);
7783}
7784
7785template <class Emitter>
7786bool Compiler<Emitter>::compileUnionAssignmentOperator(
7787 const CXXMethodDecl *MD) {
7788 if (!this->emitThis(MD))
7789 return false;
7790
7791 if (!this->emitGetParam(PT_Ptr, /*ParamIndex=*/0, MD))
7792 return false;
7793
7794 return this->emitMemcpy(MD) && this->emitRet(PT_Ptr, MD);
7795}
7796
7797template <class Emitter>
7799 if (F->getReturnType()->isDependentType())
7800 return false;
7801
7802 // Classify the return type.
7803 ReturnType = this->classify(F->getReturnType());
7804
7805 this->CompilingFunction = F;
7806
7807 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(F))
7808 return this->compileConstructor(Ctor);
7809 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(F))
7810 return this->compileDestructor(Dtor);
7811
7812 // Emit custom code if this is a lambda static invoker.
7813 if (const auto *MD = dyn_cast<CXXMethodDecl>(F)) {
7814 const RecordDecl *RD = MD->getParent();
7815
7816 if (RD->isUnion() &&
7818 return this->compileUnionAssignmentOperator(MD);
7819
7820 if (MD->isLambdaStaticInvoker())
7821 return this->emitLambdaStaticInvokerBody(MD);
7822 }
7823
7824 // Regular functions.
7825 if (const auto *Body = F->getBody())
7826 if (!visitStmt(Body))
7827 return false;
7828
7829 // Emit a guard return to protect against a code path missing one.
7830 if (F->getReturnType()->isVoidType())
7831 return this->emitRetVoid(SourceInfo{});
7832 return this->emitNoRet(SourceInfo{});
7833}
7834
7835static uint32_t getBitWidth(const Expr *E) {
7836 assert(E->refersToBitField());
7837 const auto *ME = cast<MemberExpr>(E);
7838 const auto *FD = cast<FieldDecl>(ME->getMemberDecl());
7839 return FD->getBitWidthValue();
7840}
7841
7842template <class Emitter>
7844 if (E->containsErrors())
7845 return false;
7846
7847 const Expr *SubExpr = E->getSubExpr();
7848 if (SubExpr->getType()->isAnyComplexType())
7849 return this->VisitComplexUnaryOperator(E);
7850 if (SubExpr->getType()->isVectorType())
7851 return this->VisitVectorUnaryOperator(E);
7852 if (SubExpr->getType()->isFixedPointType())
7853 return this->VisitFixedPointUnaryOperator(E);
7854 OptPrimType T = classify(SubExpr->getType());
7855
7856 switch (E->getOpcode()) {
7857 case UO_PostInc: { // x++
7858 if (!Ctx.getLangOpts().CPlusPlus14)
7859 return this->emitInvalid(E);
7860 if (!T)
7861 return this->emitError(E);
7862
7863 if (!this->visit(SubExpr))
7864 return false;
7865
7866 if (T == PT_Ptr) {
7867 if (!this->emitIncPtr(E))
7868 return false;
7869
7870 return DiscardResult ? this->emitPopPtr(E) : true;
7871 }
7872
7873 if (T == PT_Float)
7874 return DiscardResult ? this->emitIncfPop(getFPOptions(E), E)
7875 : this->emitIncf(getFPOptions(E), E);
7876
7877 if (SubExpr->refersToBitField())
7878 return DiscardResult ? this->emitIncPopBitfield(*T, E->canOverflow(),
7879 getBitWidth(SubExpr), E)
7880 : this->emitIncBitfield(*T, E->canOverflow(),
7881 getBitWidth(SubExpr), E);
7882
7883 return DiscardResult ? this->emitIncPop(*T, E->canOverflow(), E)
7884 : this->emitInc(*T, E->canOverflow(), E);
7885 }
7886 case UO_PostDec: { // x--
7887 if (!Ctx.getLangOpts().CPlusPlus14)
7888 return this->emitInvalid(E);
7889 if (!T)
7890 return this->emitError(E);
7891
7892 if (!this->visit(SubExpr))
7893 return false;
7894
7895 if (T == PT_Ptr) {
7896 if (!this->emitDecPtr(E))
7897 return false;
7898
7899 return DiscardResult ? this->emitPopPtr(E) : true;
7900 }
7901
7902 if (T == PT_Float)
7903 return DiscardResult ? this->emitDecfPop(getFPOptions(E), E)
7904 : this->emitDecf(getFPOptions(E), E);
7905
7906 if (SubExpr->refersToBitField()) {
7907 return DiscardResult ? this->emitDecPopBitfield(*T, E->canOverflow(),
7908 getBitWidth(SubExpr), E)
7909 : this->emitDecBitfield(*T, E->canOverflow(),
7910 getBitWidth(SubExpr), E);
7911 }
7912
7913 return DiscardResult ? this->emitDecPop(*T, E->canOverflow(), E)
7914 : this->emitDec(*T, E->canOverflow(), E);
7915 }
7916 case UO_PreInc: { // ++x
7917 if (!Ctx.getLangOpts().CPlusPlus14)
7918 return this->emitInvalid(E);
7919 if (!T)
7920 return this->emitError(E);
7921
7922 if (!this->visit(SubExpr))
7923 return false;
7924
7925 if (T == PT_Ptr) {
7926 if (!this->emitLoadPtr(E))
7927 return false;
7928 if (!this->emitConstUint8(1, E))
7929 return false;
7930 if (!this->emitAddOffsetUint8(E))
7931 return false;
7932 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
7933 }
7934
7935 // Post-inc and pre-inc are the same if the value is to be discarded.
7936 if (DiscardResult) {
7937 if (T == PT_Float)
7938 return this->emitIncfPop(getFPOptions(E), E);
7939 if (SubExpr->refersToBitField())
7940 return DiscardResult ? this->emitIncPopBitfield(*T, E->canOverflow(),
7941 getBitWidth(SubExpr), E)
7942 : this->emitIncBitfield(*T, E->canOverflow(),
7943 getBitWidth(SubExpr), E);
7944 return this->emitIncPop(*T, E->canOverflow(), E);
7945 }
7946
7947 if (T == PT_Float) {
7948 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
7949 if (!this->emitLoadFloat(E))
7950 return false;
7951 APFloat F(TargetSemantics, 1);
7952 if (!this->emitFloat(F, E))
7953 return false;
7954
7955 if (!this->emitAddf(getFPOptions(E), E))
7956 return false;
7957 if (!this->emitStoreFloat(E))
7958 return false;
7959 } else if (SubExpr->refersToBitField()) {
7960 assert(isIntegerOrBoolType(*T));
7961 if (!this->emitPreIncBitfield(*T, E->canOverflow(), getBitWidth(SubExpr),
7962 E))
7963 return false;
7964 } else {
7965 assert(isIntegerOrBoolType(*T));
7966 if (!this->emitPreInc(*T, E->canOverflow(), E))
7967 return false;
7968 }
7969 return E->isGLValue() || this->emitLoadPop(*T, E);
7970 }
7971 case UO_PreDec: { // --x
7972 if (!Ctx.getLangOpts().CPlusPlus14)
7973 return this->emitInvalid(E);
7974 if (!T)
7975 return this->emitError(E);
7976
7977 if (!this->visit(SubExpr))
7978 return false;
7979
7980 if (T == PT_Ptr) {
7981 if (!this->emitLoadPtr(E))
7982 return false;
7983 if (!this->emitConstUint8(1, E))
7984 return false;
7985 if (!this->emitSubOffsetUint8(E))
7986 return false;
7987 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
7988 }
7989
7990 // Post-dec and pre-dec are the same if the value is to be discarded.
7991 if (DiscardResult) {
7992 if (T == PT_Float)
7993 return this->emitDecfPop(getFPOptions(E), E);
7994 if (SubExpr->refersToBitField())
7995 return DiscardResult ? this->emitDecPopBitfield(*T, E->canOverflow(),
7996 getBitWidth(SubExpr), E)
7997 : this->emitDecBitfield(*T, E->canOverflow(),
7998 getBitWidth(SubExpr), E);
7999 return this->emitDecPop(*T, E->canOverflow(), E);
8000 }
8001
8002 if (T == PT_Float) {
8003 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
8004 if (!this->emitLoadFloat(E))
8005 return false;
8006 APFloat F(TargetSemantics, 1);
8007 if (!this->emitFloat(F, E))
8008 return false;
8009
8010 if (!this->emitSubf(getFPOptions(E), E))
8011 return false;
8012 if (!this->emitStoreFloat(E))
8013 return false;
8014 } else if (SubExpr->refersToBitField()) {
8015 assert(isIntegerOrBoolType(*T));
8016 if (!this->emitPreDecBitfield(*T, E->canOverflow(), getBitWidth(SubExpr),
8017 E))
8018 return false;
8019 } else {
8020 assert(isIntegerOrBoolType(*T));
8021 if (!this->emitPreDec(*T, E->canOverflow(), E))
8022 return false;
8023 }
8024 return E->isGLValue() || this->emitLoadPop(*T, E);
8025 }
8026 case UO_LNot: // !x
8027 if (!T)
8028 return this->emitError(E);
8029
8030 if (DiscardResult)
8031 return this->discard(SubExpr);
8032
8033 if (!this->visitBool(SubExpr))
8034 return false;
8035
8036 if (!this->emitInv(E))
8037 return false;
8038
8039 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
8040 return this->emitCast(PT_Bool, ET, E);
8041 return true;
8042 case UO_Minus: // -x
8043 if (!T)
8044 return this->emitError(E);
8045
8046 if (!this->visit(SubExpr))
8047 return false;
8048 return DiscardResult ? this->emitPop(*T, E) : this->emitNeg(*T, E);
8049 case UO_Plus: // +x
8050 if (!T)
8051 return this->emitError(E);
8052
8053 if (!this->visit(SubExpr)) // noop
8054 return false;
8055 return DiscardResult ? this->emitPop(*T, E) : true;
8056 case UO_AddrOf: // &x
8057 if (E->getType()->isMemberPointerType()) {
8058 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
8059 // member can be formed.
8060 if (DiscardResult)
8061 return true;
8062 return this->emitGetMemberPtr(cast<DeclRefExpr>(SubExpr)->getDecl(), E);
8063 }
8064 // [C11 6.5.3.2p3]: if the operand of '&' is the result of a unary '*'
8065 // operator, neither operator is evaluated and the result is as if both
8066 // were omitted. So '&*q' is just 'q' with no dereference; delegate to the
8067 // pointer operand directly instead of to the '*' (which would emit a null
8068 // check), so that e.g. '&*(int *)0' is not rejected.
8069 if (!Ctx.getLangOpts().CPlusPlus) {
8070 const Expr *Sub = SubExpr->IgnoreParens();
8071
8072 if (const auto *Deref = dyn_cast<UnaryOperator>(Sub);
8073 Deref && Deref->getOpcode() == UO_Deref) {
8074 if (DiscardResult)
8075 return this->discard(Deref->getSubExpr());
8076 return this->visit(Deref->getSubExpr()) && this->emitAddrOf(E);
8077 }
8078 }
8079 // We should already have a pointer when we get here.
8080 if (DiscardResult)
8081 return this->discard(SubExpr);
8082 return this->delegate(SubExpr) && this->emitAddrOf(E);
8083 case UO_Deref: // *x
8084 if (DiscardResult)
8085 return this->discard(SubExpr);
8086
8087 if (!this->visit(SubExpr))
8088 return false;
8089
8090 if (!SubExpr->getType()->isFunctionPointerType() && !this->emitCheckNull(E))
8091 return false;
8092
8093 if (classifyPrim(SubExpr) == PT_Ptr)
8094 return this->emitNarrowPtr(E);
8095 return true;
8096
8097 case UO_Not: // ~x
8098 if (!T)
8099 return this->emitError(E);
8100
8101 if (!this->visit(SubExpr))
8102 return false;
8103 return DiscardResult ? this->emitPop(*T, E) : this->emitComp(*T, E);
8104 case UO_Real: // __real x
8105 if (!T)
8106 return false;
8107 return this->delegate(SubExpr);
8108 case UO_Imag: { // __imag x
8109 if (!T)
8110 return false;
8111 if (!this->discard(SubExpr))
8112 return false;
8113 return DiscardResult
8114 ? true
8115 : this->visitZeroInitializer(*T, SubExpr->getType(), SubExpr);
8116 }
8117 case UO_Extension:
8118 return this->delegate(SubExpr);
8119 case UO_Coawait:
8120 assert(false && "Unhandled opcode");
8121 }
8122
8123 return false;
8124}
8125
8126template <class Emitter>
8128 const Expr *SubExpr = E->getSubExpr();
8129 assert(SubExpr->getType()->isAnyComplexType());
8130
8131 if (DiscardResult)
8132 return this->discard(SubExpr);
8133
8134 OptPrimType ResT = classify(E);
8135 auto prepareResult = [=]() -> bool {
8136 if (!ResT && !Initializing) {
8137 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
8138 if (!LocalIndex)
8139 return false;
8140 return this->emitGetPtrLocal(*LocalIndex, E);
8141 }
8142
8143 return true;
8144 };
8145
8146 // The offset of the temporary, if we created one.
8147 unsigned SubExprOffset = ~0u;
8148 auto createTemp = [=, &SubExprOffset]() -> bool {
8149 SubExprOffset =
8150 this->allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
8151 if (!this->visit(SubExpr))
8152 return false;
8153 return this->emitSetLocal(PT_Ptr, SubExprOffset, E);
8154 };
8155
8156 PrimType ElemT = classifyComplexElementType(SubExpr->getType());
8157 auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
8158 if (!this->emitGetLocal(PT_Ptr, Offset, E))
8159 return false;
8160 return this->emitArrayElemPop(ElemT, Index, E);
8161 };
8162
8163 switch (E->getOpcode()) {
8164 case UO_Minus: // -x
8165 if (!prepareResult())
8166 return false;
8167 if (!createTemp())
8168 return false;
8169 for (unsigned I = 0; I != 2; ++I) {
8170 if (!getElem(SubExprOffset, I))
8171 return false;
8172 if (!this->emitNeg(ElemT, E))
8173 return false;
8174 if (!this->emitInitElem(ElemT, I, E))
8175 return false;
8176 }
8177 break;
8178
8179 case UO_Plus: // +x
8180 case UO_AddrOf: // &x
8181 case UO_Deref: // *x
8182 return this->delegate(SubExpr);
8183
8184 case UO_LNot:
8185 if (!this->visit(SubExpr))
8186 return false;
8187 if (!this->emitComplexBoolCast(SubExpr))
8188 return false;
8189 if (!this->emitInv(E))
8190 return false;
8191 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
8192 return this->emitCast(PT_Bool, ET, E);
8193 return true;
8194
8195 case UO_Real:
8196 return this->emitComplexReal(SubExpr);
8197
8198 case UO_Imag:
8199 if (!this->visit(SubExpr))
8200 return false;
8201
8202 if (SubExpr->isLValue()) {
8203 if (!this->emitConstUint8(1, E))
8204 return false;
8205 return this->emitArrayElemPtrPopUint8(E);
8206 }
8207
8208 // Since our _Complex implementation does not map to a primitive type,
8209 // we sometimes have to do the lvalue-to-rvalue conversion here manually.
8210 return this->emitArrayElemPop(classifyPrim(E->getType()), 1, E);
8211
8212 case UO_Not: // ~x
8213 if (!this->delegate(SubExpr))
8214 return false;
8215 // Negate the imaginary component.
8216 if (!this->emitArrayElem(ElemT, 1, E))
8217 return false;
8218 if (!this->emitNeg(ElemT, E))
8219 return false;
8220 if (!this->emitInitElem(ElemT, 1, E))
8221 return false;
8222 return DiscardResult ? this->emitPopPtr(E) : true;
8223
8224 case UO_Extension:
8225 return this->delegate(SubExpr);
8226
8227 default:
8228 return this->emitInvalid(E);
8229 }
8230
8231 return true;
8232}
8233
8234template <class Emitter>
8236 const Expr *SubExpr = E->getSubExpr();
8237 assert(SubExpr->getType()->isVectorType());
8238
8239 if (DiscardResult)
8240 return this->discard(SubExpr);
8241
8242 auto UnaryOp = E->getOpcode();
8243 if (UnaryOp == UO_Extension)
8244 return this->delegate(SubExpr);
8245
8246 if (UnaryOp != UO_Plus && UnaryOp != UO_Minus && UnaryOp != UO_LNot &&
8247 UnaryOp != UO_Not && UnaryOp != UO_AddrOf)
8248 return this->emitInvalid(E);
8249
8250 // Nothing to do here.
8251 if (UnaryOp == UO_Plus || UnaryOp == UO_AddrOf)
8252 return this->delegate(SubExpr);
8253
8254 if (!Initializing) {
8255 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
8256 if (!LocalIndex)
8257 return false;
8258 if (!this->emitGetPtrLocal(*LocalIndex, E))
8259 return false;
8260 }
8261
8262 // The offset of the temporary, if we created one.
8263 unsigned SubExprOffset =
8264 this->allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
8265 if (!this->visit(SubExpr))
8266 return false;
8267 if (!this->emitSetLocal(PT_Ptr, SubExprOffset, E))
8268 return false;
8269
8270 const auto *VecTy = SubExpr->getType()->getAs<VectorType>();
8271 PrimType ElemT = classifyVectorElementType(SubExpr->getType());
8272 auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
8273 if (!this->emitGetLocal(PT_Ptr, Offset, E))
8274 return false;
8275 return this->emitArrayElemPop(ElemT, Index, E);
8276 };
8277
8278 switch (UnaryOp) {
8279 case UO_Minus:
8280 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8281 if (!getElem(SubExprOffset, I))
8282 return false;
8283 if (!this->emitNeg(ElemT, E))
8284 return false;
8285 if (!this->emitInitElem(ElemT, I, E))
8286 return false;
8287 }
8288 break;
8289 case UO_LNot: { // !x
8290 // In C++, the logic operators !, &&, || are available for vectors. !v is
8291 // equivalent to v == 0.
8292 //
8293 // The result of the comparison is a vector of the same width and number of
8294 // elements as the comparison operands with a signed integral element type.
8295 //
8296 // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html
8297 QualType ResultVecTy = E->getType();
8298 PrimType ResultVecElemT =
8299 classifyPrim(ResultVecTy->getAs<VectorType>()->getElementType());
8300 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8301 if (!getElem(SubExprOffset, I))
8302 return false;
8303 // operator ! on vectors returns -1 for 'truth', so negate it.
8304 if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
8305 return false;
8306 if (!this->emitInv(E))
8307 return false;
8308 if (!this->emitPrimCast(PT_Bool, ElemT, VecTy->getElementType(), E))
8309 return false;
8310 if (!this->emitNeg(ElemT, E))
8311 return false;
8312 if (ElemT != ResultVecElemT &&
8313 !this->emitPrimCast(ElemT, ResultVecElemT, ResultVecTy, E))
8314 return false;
8315 if (!this->emitInitElem(ResultVecElemT, I, E))
8316 return false;
8317 }
8318 break;
8319 }
8320 case UO_Not: // ~x
8321 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8322 if (!getElem(SubExprOffset, I))
8323 return false;
8324 if (ElemT == PT_Bool) {
8325 if (!this->emitInv(E))
8326 return false;
8327 } else {
8328 if (!this->emitComp(ElemT, E))
8329 return false;
8330 }
8331 if (!this->emitInitElem(ElemT, I, E))
8332 return false;
8333 }
8334 break;
8335 default:
8336 llvm_unreachable("Unsupported unary operators should be handled up front");
8337 }
8338 return true;
8339}
8340
8341template <class Emitter>
8343 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
8344 if (DiscardResult)
8345 return true;
8346 return this->emitConst(ECD->getInitVal(), E);
8347 }
8348 if (const auto *FuncDecl = dyn_cast<FunctionDecl>(D)) {
8349 if (DiscardResult)
8350 return true;
8351 const Function *F = getFunction(FuncDecl);
8352 return F && this->emitGetFnPtr(F, E);
8353 }
8354 if (const auto *TPOD = dyn_cast<TemplateParamObjectDecl>(D)) {
8355 TPOD = TPOD->getFirstDecl();
8356 if (DiscardResult)
8357 return true;
8358 if (UnsignedOrNone GlobalIndex = P.getGlobal(TPOD))
8359 return this->emitGetPtrGlobal(*GlobalIndex, E);
8360
8361 if (UnsignedOrNone Index = P.getOrCreateGlobal(TPOD)) {
8362 if (OptPrimType T = classify(TPOD->getType())) {
8363 if (!this->visitAPValue(TPOD->getValue(), *T, E))
8364 return false;
8365 return this->emitInitGlobal(*T, *Index, E);
8366 }
8367
8368 if (!this->emitGetPtrGlobal(*Index, E))
8369 return false;
8370 if (!this->visitAPValueInitializer(TPOD->getValue(), E, TPOD->getType()))
8371 return false;
8372 return this->emitFinishInit(E);
8373 }
8374 return false;
8375 }
8376
8377 // References are implemented via pointers, so when we see a DeclRefExpr
8378 // pointing to a reference, we need to get its value directly (i.e. the
8379 // pointer to the actual value) instead of a pointer to the pointer to the
8380 // value.
8381 QualType DeclType = D->getType();
8382 bool IsReference = DeclType->isReferenceType();
8383
8384 auto maybePopPtr = [&]() -> bool {
8385 if (DiscardResult)
8386 return this->emitPopPtr(E);
8387 return true;
8388 };
8389
8390 // Function parameters.
8391 // Note that it's important to check them first since we might have a local
8392 // variable created for a ParmVarDecl as well.
8393 if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
8394 if (DiscardResult)
8395 return true;
8396
8397 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
8398 !DeclType->isIntegralOrEnumerationType()) {
8399 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8400 /*InitializerFailed=*/false, E);
8401 }
8402 if (auto It = this->Params.find(PVD); It != this->Params.end()) {
8403 if (IsReference || !It->second.IsPtr)
8404 return this->emitGetParam(classifyPrim(E), It->second.Index, E);
8405
8406 return this->emitGetPtrParam(It->second.Index, E);
8407 }
8408
8409 if (!Ctx.getLangOpts().CPlusPlus23 && IsReference && !Locals.contains(D))
8410 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8411 /*InitializerFailed=*/false, E);
8412 }
8413
8414 // Local variables.
8415 if (auto It = Locals.find(D); It != Locals.end()) {
8416 const unsigned Offset = It->second.Offset;
8417 if (IsReference) {
8418 assert(classifyPrim(E) == PT_Ptr);
8419 return this->emitGetRefLocal(Offset, E) && maybePopPtr();
8420 }
8421 return this->emitGetPtrLocal(Offset, E) && maybePopPtr();
8422 }
8423 // Global variables.
8424 if (auto GlobalIndex = P.getGlobal(D)) {
8425 if (IsReference) {
8426 if (!Ctx.getLangOpts().CPlusPlus11)
8427 return this->emitGetGlobal(classifyPrim(E), *GlobalIndex, E);
8428 if (!Ctx.getLangOpts().CPlusPlus23)
8429 return this->emitGetGlobalUnchecked(classifyPrim(E), *GlobalIndex, E);
8430
8431 return this->emitGetRefGlobal(*GlobalIndex, E) && maybePopPtr();
8432 }
8433
8434 return this->emitGetPtrGlobal(*GlobalIndex, E) && maybePopPtr();
8435 }
8436
8437 // In case we need to re-visit a declaration.
8438 auto revisit = [&](const VarDecl *VD,
8439 bool IsConstexprUnknown = true) -> bool {
8441 IsConstexprUnknown);
8442 if constexpr (std::is_same_v<Emitter, EvalEmitter>) {
8443 if (!this->emitPushCC(VD->hasConstantInitialization(), E))
8444 return false;
8445 }
8446 auto VarState = this->visitDecl(VD);
8447
8448 if constexpr (std::is_same_v<Emitter, EvalEmitter>) {
8449 if (!this->emitPopCC(E))
8450 return false;
8451 }
8452
8453 if (VarState.notCreated())
8454 return true;
8455 if (!VarState)
8456 return false;
8457 // Retry.
8458 return this->visitDeclRef(D, E);
8459 };
8460
8461 if constexpr (!std::is_same_v<Emitter, EvalEmitter>) {
8462 // Lambda captures.
8463 if (auto It = this->LambdaCaptures.find(D);
8464 It != this->LambdaCaptures.end()) {
8465 auto [Offset, IsPtr] = It->second;
8466
8467 if (IsPtr)
8468 return this->emitGetThisFieldPtr(Offset, E) && maybePopPtr();
8469 return this->emitGetPtrThisField(Offset, E) && maybePopPtr();
8470 }
8471 }
8472
8473 if (const auto *DRE = dyn_cast<DeclRefExpr>(E);
8474 DRE && DRE->refersToEnclosingVariableOrCapture()) {
8475 if (const auto *VD = dyn_cast<VarDecl>(D); VD && VD->isInitCapture())
8476 return revisit(VD);
8477 }
8478
8479 if (const auto *BD = dyn_cast<BindingDecl>(D))
8480 return this->delegate(BD->getBinding());
8481
8482 // Avoid infinite recursion.
8483 if (D == InitializingDecl) {
8484 if (DiscardResult)
8485 return true;
8486 return this->emitDummyPtr(D, E);
8487 }
8488
8489 // Try to lazily visit (or emit dummy pointers for) declarations
8490 // we haven't seen yet.
8491 const auto *VD = dyn_cast<VarDecl>(D);
8492 if (!VD)
8493 return this->emitError(E);
8494
8495 // For C.
8496 if (!Ctx.getLangOpts().CPlusPlus) {
8497 if (VD->getInit() && !VD->getInit()->isValueDependent() &&
8498 DeclType.isConstant(Ctx.getASTContext()) && !VD->isWeak() &&
8499 VD->evaluateValue())
8500 return revisit(VD, /*IsConstexprUnknown=*/false);
8501
8502 if (DiscardResult)
8503 return true;
8504 return this->emitDummyPtr(D, E);
8505 }
8506
8507 // ... and C++.
8508 const auto typeShouldBeVisited = [&](QualType T) -> bool {
8509 if (T.isConstant(Ctx.getASTContext()))
8510 return true;
8511 return T->isReferenceType();
8512 };
8513
8514 if ((VD->hasGlobalStorage() || VD->isStaticDataMember()) &&
8515 typeShouldBeVisited(DeclType)) {
8516 if (const Expr *Init = VD->getAnyInitializer();
8517 Init && !Init->isValueDependent()) {
8518 // Whether or not the evaluation is successul doesn't really matter
8519 // here -- we will create a global variable in any case, and that
8520 // will have the state of initializer evaluation attached.
8522 (void)Init->EvaluateAsInitializer(Ctx.getASTContext(), VD, Result, true);
8523 return this->visitDeclRef(D, E);
8524 }
8525 return revisit(VD, !VD->isConstexpr() && DeclType->isReferenceType());
8526 }
8527
8528 // FIXME: The evaluateValue() check here is a little ridiculous, since
8529 // it will ultimately call into Context::evaluateAsInitializer(). In
8530 // other words, we're evaluating the initializer, just to know if we can
8531 // evaluate the initializer.
8532 if (VD->isLocalVarDecl() && typeShouldBeVisited(DeclType) && VD->getInit() &&
8533 !VD->getInit()->isValueDependent()) {
8534 if (VD->evaluateValue()) {
8535 bool IsConstexprUnknown = !DeclType.isConstant(Ctx.getASTContext()) &&
8536 !DeclType->isReferenceType();
8537 // Revisit the variable declaration, but make sure it's associated with a
8538 // different evaluation, so e.g. mutable reads don't work on it.
8539 EvalIDScope _(Ctx);
8540 return revisit(VD, IsConstexprUnknown);
8541 } else if (Ctx.getLangOpts().CPlusPlus23 && IsReference)
8542 return revisit(VD, /*IsConstexprUnknown=*/true);
8543
8544 if (IsReference)
8545 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8546 /*InitializerFailed=*/true, E);
8547 }
8548
8549 if (DiscardResult)
8550 return true;
8551 return this->emitDummyPtr(
8552 D, E, Ctx.getLangOpts().CPlusPlus23 && DeclType->isReferenceType());
8553}
8554
8555template <class Emitter>
8557 const auto *D = E->getDecl();
8558 return this->visitDeclRef(D, E);
8559}
8560
8561template <class Emitter>
8563 const DesignatedInitUpdateExpr *E) {
8564 if (!this->visitInitializer(E->getBase()))
8565 return false;
8566 return this->visitInitializer(E->getUpdater());
8567}
8568
8569template <class Emitter> bool Compiler<Emitter>::emitCleanup() {
8570 for (VariableScope<Emitter> *C = VarScope; C; C = C->getParent()) {
8571 if (!C->destroyLocals())
8572 return false;
8573 }
8574 return true;
8575}
8576
8577template <class Emitter>
8578unsigned Compiler<Emitter>::collectBaseOffset(const QualType BaseType,
8579 const QualType DerivedType) {
8580 const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
8581 if (const auto *R = Ty->getPointeeCXXRecordDecl())
8582 return R;
8583 return Ty->getAsCXXRecordDecl();
8584 };
8585 const CXXRecordDecl *BaseDecl = extractRecordDecl(BaseType);
8586 const CXXRecordDecl *DerivedDecl = extractRecordDecl(DerivedType);
8587
8588 return Ctx.collectBaseOffset(BaseDecl, DerivedDecl);
8589}
8590
8591/// Emit casts from a PrimType to another PrimType.
8592template <class Emitter>
8593bool Compiler<Emitter>::emitPrimCast(PrimType FromT, PrimType ToT,
8594 QualType ToQT, const Expr *E) {
8595
8596 if (FromT == PT_Float) {
8597 // Floating to floating.
8598 if (ToT == PT_Float) {
8599 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
8600 return this->emitCastFP(ToSem, getRoundingMode(E), E);
8601 }
8602
8603 if (ToT == PT_IntAP)
8604 return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(ToQT),
8605 getFPOptions(E), E);
8606 if (ToT == PT_IntAPS)
8607 return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(ToQT),
8608 getFPOptions(E), E);
8609
8610 // Float to integral.
8611 if (isIntegerOrBoolType(ToT) || ToT == PT_Bool)
8612 return this->emitCastFloatingIntegral(ToT, getFPOptions(E), E);
8613 }
8614
8615 if (isIntegerOrBoolType(FromT) || FromT == PT_Bool) {
8616 if (ToT == PT_IntAP)
8617 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
8618 if (ToT == PT_IntAPS)
8619 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
8620
8621 // Integral to integral.
8622 if (isIntegerOrBoolType(ToT) || ToT == PT_Bool)
8623 return FromT != ToT ? this->emitCast(FromT, ToT, E) : true;
8624
8625 if (ToT == PT_Float) {
8626 // Integral to floating.
8627 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
8628 return this->emitCastIntegralFloating(FromT, ToSem, getFPOptions(E), E);
8629 }
8630 }
8631
8632 return false;
8633}
8634
8635template <class Emitter>
8636bool Compiler<Emitter>::emitIntegralCast(PrimType FromT, PrimType ToT,
8637 QualType ToQT, const Expr *E) {
8638 assert(FromT != ToT);
8639
8640 if (ToT == PT_IntAP)
8641 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
8642 if (ToT == PT_IntAPS)
8643 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
8644
8645 return this->emitCast(FromT, ToT, E);
8646}
8647
8648/// Emits __real(SubExpr)
8649template <class Emitter>
8650bool Compiler<Emitter>::emitComplexReal(const Expr *SubExpr) {
8651 assert(SubExpr->getType()->isAnyComplexType());
8652
8653 if (DiscardResult)
8654 return this->discard(SubExpr);
8655
8656 if (!this->visit(SubExpr))
8657 return false;
8658 if (SubExpr->isLValue()) {
8659 if (!this->emitConstUint8(0, SubExpr))
8660 return false;
8661 return this->emitArrayElemPtrPopUint8(SubExpr);
8662 }
8663
8664 // Rvalue, load the actual element.
8665 return this->emitArrayElemPop(classifyComplexElementType(SubExpr->getType()),
8666 0, SubExpr);
8667}
8668
8669template <class Emitter>
8670bool Compiler<Emitter>::emitComplexBoolCast(const Expr *E) {
8671 assert(!DiscardResult);
8672 PrimType ElemT = classifyComplexElementType(E->getType());
8673 // We emit the expression (__real(E) != 0 || __imag(E) != 0)
8674 // for us, that means (bool)E[0] || (bool)E[1]
8675 if (!this->emitArrayElem(ElemT, 0, E))
8676 return false;
8677 if (ElemT == PT_Float) {
8678 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
8679 return false;
8680 } else {
8681 if (!this->emitCast(ElemT, PT_Bool, E))
8682 return false;
8683 }
8684
8685 // We now have the bool value of E[0] on the stack.
8686 LabelTy LabelTrue = this->getLabel();
8687 if (!this->jumpTrue(LabelTrue, E))
8688 return false;
8689
8690 if (!this->emitArrayElemPop(ElemT, 1, E))
8691 return false;
8692 if (ElemT == PT_Float) {
8693 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
8694 return false;
8695 } else {
8696 if (!this->emitCast(ElemT, PT_Bool, E))
8697 return false;
8698 }
8699 // Leave the boolean value of E[1] on the stack.
8700 LabelTy EndLabel = this->getLabel();
8701 this->jump(EndLabel, E);
8702
8703 this->emitLabel(LabelTrue);
8704 if (!this->emitPopPtr(E))
8705 return false;
8706 if (!this->emitConstBool(true, E))
8707 return false;
8708
8709 this->fallthrough(EndLabel);
8710 this->emitLabel(EndLabel);
8711
8712 return true;
8713}
8714
8715template <class Emitter>
8716bool Compiler<Emitter>::emitComplexComparison(const Expr *LHS, const Expr *RHS,
8717 const BinaryOperator *E) {
8718 assert(E->isComparisonOp());
8719 assert(!Initializing);
8720 if (DiscardResult)
8721 return this->discard(LHS) && this->discard(RHS);
8722
8723 PrimType ElemT;
8724 bool LHSIsComplex;
8725 unsigned LHSOffset;
8726 if (LHS->getType()->isAnyComplexType()) {
8727 LHSIsComplex = true;
8728 ElemT = classifyComplexElementType(LHS->getType());
8729 LHSOffset = allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true);
8730 if (!this->visit(LHS))
8731 return false;
8732 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
8733 return false;
8734 } else {
8735 LHSIsComplex = false;
8736 PrimType LHST = classifyPrim(LHS->getType());
8737 LHSOffset = this->allocateLocalPrimitive(LHS, LHST, /*IsConst=*/true);
8738 if (!this->visit(LHS))
8739 return false;
8740 if (!this->emitSetLocal(LHST, LHSOffset, E))
8741 return false;
8742 }
8743
8744 bool RHSIsComplex;
8745 unsigned RHSOffset;
8746 if (RHS->getType()->isAnyComplexType()) {
8747 RHSIsComplex = true;
8748 ElemT = classifyComplexElementType(RHS->getType());
8749 RHSOffset = allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true);
8750 if (!this->visit(RHS))
8751 return false;
8752 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
8753 return false;
8754 } else {
8755 RHSIsComplex = false;
8756 PrimType RHST = classifyPrim(RHS->getType());
8757 RHSOffset = this->allocateLocalPrimitive(RHS, RHST, /*IsConst=*/true);
8758 if (!this->visit(RHS))
8759 return false;
8760 if (!this->emitSetLocal(RHST, RHSOffset, E))
8761 return false;
8762 }
8763
8764 auto getElem = [&](unsigned LocalOffset, unsigned Index,
8765 bool IsComplex) -> bool {
8766 if (IsComplex) {
8767 if (!this->emitGetLocal(PT_Ptr, LocalOffset, E))
8768 return false;
8769 return this->emitArrayElemPop(ElemT, Index, E);
8770 }
8771 return this->emitGetLocal(ElemT, LocalOffset, E);
8772 };
8773
8774 for (unsigned I = 0; I != 2; ++I) {
8775 // Get both values.
8776 if (!getElem(LHSOffset, I, LHSIsComplex))
8777 return false;
8778 if (!getElem(RHSOffset, I, RHSIsComplex))
8779 return false;
8780 // And compare them.
8781 if (!this->emitEQ(ElemT, E))
8782 return false;
8783
8784 if (!this->emitCastBoolUint8(E))
8785 return false;
8786 }
8787
8788 // We now have two bool values on the stack. Compare those.
8789 if (!this->emitAddUint8(E))
8790 return false;
8791 if (!this->emitConstUint8(2, E))
8792 return false;
8793
8794 if (E->getOpcode() == BO_EQ) {
8795 if (!this->emitEQUint8(E))
8796 return false;
8797 } else if (E->getOpcode() == BO_NE) {
8798 if (!this->emitNEUint8(E))
8799 return false;
8800 } else
8801 return false;
8802
8803 // In C, this returns an int.
8804 if (PrimType ResT = classifyPrim(E->getType()); ResT != PT_Bool)
8805 return this->emitCast(PT_Bool, ResT, E);
8806 return true;
8807}
8808
8809/// When calling this, we have a pointer of the local-to-destroy
8810/// on the stack.
8811/// Emit destruction of record types (or arrays of record types).
8812template <class Emitter>
8813bool Compiler<Emitter>::emitRecordDestructionPop(const Record *R,
8814 SourceInfo Loc) {
8815 assert(R);
8816 assert(!R->hasTrivialDtor());
8817 const CXXDestructorDecl *Dtor = R->getDestructor();
8818 assert(Dtor);
8819 const Function *DtorFunc = getFunction(Dtor);
8820 if (!DtorFunc)
8821 return false;
8822 assert(DtorFunc->hasThisPointer());
8823 assert(DtorFunc->getNumParams() == 1);
8824 return this->emitCall(DtorFunc, 0, Loc);
8825}
8826/// When calling this, we have a pointer of the local-to-destroy
8827/// on the stack.
8828/// Emit destruction of record types (or arrays of record types).
8829template <class Emitter>
8830bool Compiler<Emitter>::emitDestructionPop(const Descriptor *Desc,
8831 SourceInfo Loc) {
8832 assert(Desc);
8833 assert(!Desc->hasTrivialDtor());
8834
8835 // Arrays.
8836 if (Desc->isArray()) {
8837 const Descriptor *ElemDesc = Desc->ElemDesc;
8838 assert(ElemDesc);
8839
8840 unsigned N = Desc->getNumElems();
8841 if (N == 0)
8842 return this->emitPopPtr(Loc);
8843
8844 for (ssize_t I = N - 1; I >= 1; --I) {
8845 if (!this->emitConstUint64(I, Loc))
8846 return false;
8847 if (!this->emitArrayElemPtrUint64(Loc))
8848 return false;
8849 if (!this->emitDestructionPop(ElemDesc, Loc))
8850 return false;
8851 }
8852 // Last iteration, removes the instance pointer from the stack.
8853 if (!this->emitConstUint64(0, Loc))
8854 return false;
8855 if (!this->emitArrayElemPtrPopUint64(Loc))
8856 return false;
8857 return this->emitDestructionPop(ElemDesc, Loc);
8858 }
8859
8860 assert(Desc->ElemRecord);
8861 assert(!Desc->ElemRecord->hasTrivialDtor());
8862 return this->emitRecordDestructionPop(Desc->ElemRecord, Loc);
8863}
8864
8865/// Create a dummy pointer for the given decl (or expr) and
8866/// push a pointer to it on the stack.
8867template <class Emitter>
8868bool Compiler<Emitter>::emitDummyPtr(DeclOrExpr D, const Expr *E, bool CU) {
8869 assert(!DiscardResult && "Should've been checked before");
8870 return this->emitGetOpaquePtr(D, CU, E);
8871}
8872
8873template <class Emitter>
8874bool Compiler<Emitter>::emitFloat(const APFloat &F, SourceInfo Info) {
8875 if (Floating::singleWord(F.getSemantics()))
8876 return this->emitConstFloat(Floating(F), Info);
8877
8878 APInt I = F.bitcastToAPInt();
8879 return this->emitConstFloat(
8880 Floating(const_cast<uint64_t *>(I.getRawData()),
8881 llvm::APFloatBase::SemanticsToEnum(F.getSemantics())),
8882 Info);
8883}
8884
8885// This function is constexpr if and only if To, From, and the types of
8886// all subobjects of To and From are types T such that...
8887// (3.1) - is_union_v<T> is false;
8888// (3.2) - is_pointer_v<T> is false;
8889// (3.3) - is_member_pointer_v<T> is false;
8890// (3.4) - is_volatile_v<T> is false; and
8891// (3.5) - T has no non-static data members of reference type
8892template <class Emitter>
8893bool Compiler<Emitter>::emitBuiltinBitCast(const CastExpr *E) {
8894 const Expr *SubExpr = E->getSubExpr();
8895 QualType FromType = SubExpr->getType();
8896 QualType ToType = E->getType();
8897 OptPrimType ToT = classify(ToType);
8898
8899 assert(!ToType->isReferenceType());
8900
8901 // Prepare storage for the result in case we discard.
8902 if (DiscardResult && !Initializing && !ToT) {
8903 UnsignedOrNone LocalIndex = allocateLocal(E);
8904 if (!LocalIndex)
8905 return false;
8906 if (!this->emitGetPtrLocal(*LocalIndex, E))
8907 return false;
8908 }
8909
8910 // Get a pointer to the value-to-cast on the stack.
8911 // For CK_LValueToRValueBitCast, this is always an lvalue and
8912 // we later assume it to be one (i.e. a PT_Ptr). However,
8913 // we call this function for other utility methods where
8914 // a bitcast might be useful, so convert it to a PT_Ptr in that case.
8915 if (SubExpr->isGLValue() || FromType->isVectorType()) {
8916 if (!this->visit(SubExpr))
8917 return false;
8918 } else if (OptPrimType FromT = classify(SubExpr)) {
8919 unsigned TempOffset =
8920 allocateLocalPrimitive(SubExpr, *FromT, /*IsConst=*/true);
8921 if (!this->visit(SubExpr))
8922 return false;
8923 if (!this->emitSetLocal(*FromT, TempOffset, E))
8924 return false;
8925 if (!this->emitGetPtrLocal(TempOffset, E))
8926 return false;
8927 } else {
8928 return false;
8929 }
8930
8931 if (!ToT) {
8932 if (!this->emitBitCast(E))
8933 return false;
8934 return DiscardResult ? this->emitPopPtr(E) : true;
8935 }
8936 assert(ToT);
8937
8938 const llvm::fltSemantics *TargetSemantics = nullptr;
8939 if (ToT == PT_Float)
8940 TargetSemantics = &Ctx.getFloatSemantics(ToType);
8941
8942 // Conversion to a primitive type. FromType can be another
8943 // primitive type, or a record/array.
8944 bool ToTypeIsUChar = (ToType->isSpecificBuiltinType(BuiltinType::UChar) ||
8945 ToType->isSpecificBuiltinType(BuiltinType::Char_U));
8946 uint32_t ResultBitWidth = std::max(Ctx.getBitWidth(ToType), 8u);
8947
8948 if (!this->emitBitCastPrim(*ToT, ToTypeIsUChar || ToType->isStdByteType(),
8949 ResultBitWidth, TargetSemantics,
8950 ToType.getTypePtr(), E))
8951 return false;
8952
8953 if (DiscardResult)
8954 return this->emitPop(*ToT, E);
8955
8956 return true;
8957}
8958
8959/// Replicate a scalar value into every scalar element of an aggregate.
8960/// The scalar is stored in a local at \p SrcOffset and a pointer to the
8961/// destination must be on top of the interpreter stack. Each element receives
8962/// the scalar, cast to its own type.
8963template <class Emitter>
8964bool Compiler<Emitter>::emitHLSLAggregateSplat(PrimType SrcT,
8965 unsigned SrcOffset,
8966 QualType DestType,
8967 const Expr *E) {
8968 // Vectors and matrices are treated as flat sequences of elements.
8969 unsigned NumElems = 0;
8970 QualType ElemType;
8971 if (const auto *VT = DestType->getAs<VectorType>()) {
8972 NumElems = VT->getNumElements();
8973 ElemType = VT->getElementType();
8974 } else if (const auto *MT = DestType->getAs<ConstantMatrixType>()) {
8975 NumElems = MT->getNumElementsFlattened();
8976 ElemType = MT->getElementType();
8977 }
8978 if (NumElems > 0) {
8979 PrimType ElemT = classifyPrim(ElemType);
8980 for (unsigned I = 0; I != NumElems; ++I) {
8981 if (!this->emitGetLocal(SrcT, SrcOffset, E))
8982 return false;
8983 if (!this->emitPrimCast(SrcT, ElemT, ElemType, E))
8984 return false;
8985 if (!this->emitInitElem(ElemT, I, E))
8986 return false;
8987 }
8988 return true;
8989 }
8990
8991 // Arrays: primitive elements are filled directly; composite elements
8992 // require recursion into each sub-aggregate.
8993 if (const auto *AT = DestType->getAsArrayTypeUnsafe()) {
8994 const auto *CAT = cast<ConstantArrayType>(AT);
8995 QualType ArrElemType = CAT->getElementType();
8996 unsigned ArrSize = CAT->getZExtSize();
8997
8998 if (OptPrimType ElemT = classify(ArrElemType)) {
8999 for (unsigned I = 0; I != ArrSize; ++I) {
9000 if (!this->emitGetLocal(SrcT, SrcOffset, E))
9001 return false;
9002 if (!this->emitPrimCast(SrcT, *ElemT, ArrElemType, E))
9003 return false;
9004 if (!this->emitInitElem(*ElemT, I, E))
9005 return false;
9006 }
9007 } else {
9008 for (unsigned I = 0; I != ArrSize; ++I) {
9009 if (!this->emitConstUint32(I, E))
9010 return false;
9011 if (!this->emitArrayElemPtrUint32(E))
9012 return false;
9013 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, ArrElemType, E))
9014 return false;
9015 if (!this->emitFinishInitPop(E))
9016 return false;
9017 }
9018 }
9019 return true;
9020 }
9021
9022 // Records: fill base classes first, then named fields in declaration
9023 // order.
9024 if (DestType->isRecordType()) {
9025 const Record *R = getRecord(DestType);
9026 if (!R)
9027 return false;
9028
9029 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
9030 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
9031 const Record::Base *B = R->getBase(BS.getType());
9032 assert(B);
9033 if (!this->emitGetPtrBase(B->Offset, E))
9034 return false;
9035 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, BS.getType(), E))
9036 return false;
9037 if (!this->emitFinishInitPop(E))
9038 return false;
9039 }
9040 }
9041
9042 for (const Record::Field &F : R->fields()) {
9043 if (F.isUnnamedBitField())
9044 continue;
9045
9046 QualType FieldType = F.Decl->getType();
9047 if (OptPrimType FieldT = F.T) {
9048 if (!this->emitGetLocal(SrcT, SrcOffset, E))
9049 return false;
9050 if (!this->emitPrimCast(SrcT, *FieldT, FieldType, E))
9051 return false;
9052 if (F.isBitField()) {
9053 if (!this->emitInitBitField(*FieldT, F.Offset, F.bitWidth(), E))
9054 return false;
9055 } else {
9056 if (!this->emitInitField(*FieldT, F.Offset, E))
9057 return false;
9058 }
9059 } else {
9060 if (!this->emitGetPtrField(F.Offset, E))
9061 return false;
9062 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, FieldType, E))
9063 return false;
9064 if (!this->emitPopPtr(E))
9065 return false;
9066 }
9067 }
9068 return true;
9069 }
9070
9071 return false;
9072}
9073
9074/// Return the total number of scalar elements in a type. This is used
9075/// to cap how many source elements are extracted during an elementwise cast,
9076/// so we never flatten more than the destination can hold.
9077template <class Emitter>
9078unsigned Compiler<Emitter>::countHLSLFlatElements(QualType Ty) {
9079 // Vector and matrix types are treated as flat sequences of elements.
9080 if (const auto *VT = Ty->getAs<VectorType>())
9081 return VT->getNumElements();
9082 if (const auto *MT = Ty->getAs<ConstantMatrixType>())
9083 return MT->getNumElementsFlattened();
9084 // Arrays: total count is array size * scalar elements per element.
9085 if (const auto *AT = Ty->getAsArrayTypeUnsafe()) {
9086 const auto *CAT = cast<ConstantArrayType>(AT);
9087 return CAT->getZExtSize() * countHLSLFlatElements(CAT->getElementType());
9088 }
9089 // Records: sum scalar element counts of base classes and named fields.
9090 if (Ty->isRecordType()) {
9091 const Record *R = getRecord(Ty);
9092 if (!R)
9093 return 0;
9094 unsigned Count = 0;
9095 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
9096 for (const CXXBaseSpecifier &BS : CXXRD->bases())
9097 Count += countHLSLFlatElements(BS.getType());
9098 }
9099 for (const Record::Field &F : R->fields()) {
9100 if (F.isUnnamedBitField())
9101 continue;
9102 Count += countHLSLFlatElements(F.Decl->getType());
9103 }
9104 return Count;
9105 }
9106 // Scalar primitive types contribute one element.
9107 if (canClassify(Ty))
9108 return 1;
9109 return 0;
9110}
9111
9112/// Walk a source aggregate and extract every scalar element into its own local
9113/// variable. The results are appended to \p Elements in declaration order,
9114/// stopping once \p MaxElements have been collected. A pointer to the
9115/// source aggregate must be stored in the local at \p SrcOffset.
9116template <class Emitter>
9117bool Compiler<Emitter>::emitHLSLFlattenAggregate(
9118 QualType SrcType, unsigned SrcOffset,
9119 SmallVectorImpl<HLSLFlatElement> &Elements, unsigned MaxElements,
9120 const Expr *E) {
9121
9122 // Save a scalar value from the stack into a new local and record it.
9123 auto saveToLocal = [&](PrimType T) -> bool {
9124 unsigned Offset = allocateLocalPrimitive(E, T, /*IsConst=*/true);
9125 if (!this->emitSetLocal(T, Offset, E))
9126 return false;
9127 Elements.push_back({Offset, T});
9128 return true;
9129 };
9130
9131 // Save a pointer from the stack into a new local for later use.
9132 auto savePtrToLocal = [&]() -> UnsignedOrNone {
9133 unsigned Offset = allocateLocalPrimitive(E, PT_Ptr, /*IsConst=*/true);
9134 if (!this->emitSetLocal(PT_Ptr, Offset, E))
9135 return std::nullopt;
9136 return Offset;
9137 };
9138
9139 // Vectors and matrices are flat sequences of elements.
9140 unsigned NumElems = 0;
9141 QualType ElemType;
9142 if (const auto *VT = SrcType->getAs<VectorType>()) {
9143 NumElems = VT->getNumElements();
9144 ElemType = VT->getElementType();
9145 } else if (const auto *MT = SrcType->getAs<ConstantMatrixType>()) {
9146 NumElems = MT->getNumElementsFlattened();
9147 ElemType = MT->getElementType();
9148 }
9149 if (NumElems > 0) {
9150 PrimType ElemT = classifyPrim(ElemType);
9151 for (unsigned I = 0; I != NumElems && Elements.size() < MaxElements; ++I) {
9152 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9153 return false;
9154 if (!this->emitArrayElemPop(ElemT, I, E))
9155 return false;
9156 if (!saveToLocal(ElemT))
9157 return false;
9158 }
9159 return true;
9160 }
9161
9162 // Arrays: primitive elements are extracted directly; composite elements
9163 // require recursion into each sub-aggregate.
9164 if (const auto *AT = SrcType->getAsArrayTypeUnsafe()) {
9165 const auto *CAT = cast<ConstantArrayType>(AT);
9166 QualType ArrElemType = CAT->getElementType();
9167 unsigned ArrSize = CAT->getZExtSize();
9168
9169 if (OptPrimType ElemT = classify(ArrElemType)) {
9170 for (unsigned I = 0; I != ArrSize && Elements.size() < MaxElements; ++I) {
9171 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9172 return false;
9173 if (!this->emitArrayElemPop(*ElemT, I, E))
9174 return false;
9175 if (!saveToLocal(*ElemT))
9176 return false;
9177 }
9178 } else {
9179 for (unsigned I = 0; I != ArrSize && Elements.size() < MaxElements; ++I) {
9180 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9181 return false;
9182 if (!this->emitConstUint32(I, E))
9183 return false;
9184 if (!this->emitArrayElemPtrPopUint32(E))
9185 return false;
9186 UnsignedOrNone ElemPtrOffset = savePtrToLocal();
9187 if (!ElemPtrOffset)
9188 return false;
9189 if (!emitHLSLFlattenAggregate(ArrElemType, *ElemPtrOffset, Elements,
9190 MaxElements, E))
9191 return false;
9192 }
9193 }
9194 return true;
9195 }
9196
9197 // Records: base classes come first, then named fields in declaration
9198 // order.
9199 if (SrcType->isRecordType()) {
9200 const Record *R = getRecord(SrcType);
9201 if (!R)
9202 return false;
9203
9204 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
9205 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
9206 if (Elements.size() >= MaxElements)
9207 break;
9208 const Record::Base *B = R->getBase(BS.getType());
9209 assert(B);
9210 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9211 return false;
9212 if (!this->emitGetPtrBasePop(B->Offset, /*NullOK=*/false, E))
9213 return false;
9214 UnsignedOrNone BasePtrOffset = savePtrToLocal();
9215 if (!BasePtrOffset)
9216 return false;
9217 if (!emitHLSLFlattenAggregate(BS.getType(), *BasePtrOffset, Elements,
9218 MaxElements, E))
9219 return false;
9220 }
9221 }
9222
9223 for (const Record::Field &F : R->fields()) {
9224 if (Elements.size() >= MaxElements)
9225 break;
9226 if (F.isUnnamedBitField())
9227 continue;
9228
9229 QualType FieldType = F.Decl->getType();
9230 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9231 return false;
9232 if (!this->emitGetPtrFieldPop(F.Offset, E))
9233 return false;
9234
9235 if (OptPrimType FieldT = F.T) {
9236 if (!this->emitLoadPop(*FieldT, E))
9237 return false;
9238 if (!saveToLocal(*FieldT))
9239 return false;
9240 } else {
9241 UnsignedOrNone FieldPtrOffset = savePtrToLocal();
9242 if (!FieldPtrOffset)
9243 return false;
9244 if (!emitHLSLFlattenAggregate(FieldType, *FieldPtrOffset, Elements,
9245 MaxElements, E))
9246 return false;
9247 }
9248 }
9249 return true;
9250 }
9251
9252 return false;
9253}
9254
9255/// Populate an HLSL aggregate from a flat list of previously extracted source
9256/// elements, casting each to the corresponding destination element type.
9257/// \p ElemIdx tracks the current position in \p Elements and is advanced as
9258/// elements are consumed. A pointer to the destination must be on top of the
9259/// interpreter stack.
9260template <class Emitter>
9261bool Compiler<Emitter>::emitHLSLConstructAggregate(
9262 QualType DestType, ArrayRef<HLSLFlatElement> Elements, unsigned &ElemIdx,
9263 const Expr *E) {
9264
9265 // Consume the next source element, cast it, and leave it on the stack.
9266 auto loadAndCast = [&](PrimType DestT, QualType DestQT) -> bool {
9267 const auto &Src = Elements[ElemIdx++];
9268 if (!this->emitGetLocal(Src.Type, Src.LocalOffset, E))
9269 return false;
9270 return this->emitPrimCast(Src.Type, DestT, DestQT, E);
9271 };
9272
9273 // Vectors and matrices are flat sequences of elements.
9274 unsigned NumElems = 0;
9275 QualType ElemType;
9276 if (const auto *VT = DestType->getAs<VectorType>()) {
9277 NumElems = VT->getNumElements();
9278 ElemType = VT->getElementType();
9279 } else if (const auto *MT = DestType->getAs<ConstantMatrixType>()) {
9280 NumElems = MT->getNumElementsFlattened();
9281 ElemType = MT->getElementType();
9282 }
9283 if (NumElems > 0) {
9284 PrimType DestElemT = classifyPrim(ElemType);
9285 for (unsigned I = 0; I != NumElems; ++I) {
9286 if (!loadAndCast(DestElemT, ElemType))
9287 return false;
9288 if (!this->emitInitElem(DestElemT, I, E))
9289 return false;
9290 }
9291 return true;
9292 }
9293
9294 // Arrays: primitive elements are filled directly; composite elements
9295 // require recursion into each sub-aggregate.
9296 if (const auto *AT = DestType->getAsArrayTypeUnsafe()) {
9297 const auto *CAT = cast<ConstantArrayType>(AT);
9298 QualType ArrElemType = CAT->getElementType();
9299 unsigned ArrSize = CAT->getZExtSize();
9300
9301 if (OptPrimType ElemT = classify(ArrElemType)) {
9302 for (unsigned I = 0; I != ArrSize; ++I) {
9303 if (!loadAndCast(*ElemT, ArrElemType))
9304 return false;
9305 if (!this->emitInitElem(*ElemT, I, E))
9306 return false;
9307 }
9308 } else {
9309 for (unsigned I = 0; I != ArrSize; ++I) {
9310 if (!this->emitConstUint32(I, E))
9311 return false;
9312 if (!this->emitArrayElemPtrUint32(E))
9313 return false;
9314 if (!emitHLSLConstructAggregate(ArrElemType, Elements, ElemIdx, E))
9315 return false;
9316 if (!this->emitFinishInitPop(E))
9317 return false;
9318 }
9319 }
9320 return true;
9321 }
9322
9323 // Records: base classes come first, then named fields in declaration
9324 // order.
9325 if (DestType->isRecordType()) {
9326 const Record *R = getRecord(DestType);
9327 if (!R)
9328 return false;
9329
9330 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
9331 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
9332 const Record::Base *B = R->getBase(BS.getType());
9333 assert(B);
9334 if (!this->emitGetPtrBase(B->Offset, E))
9335 return false;
9336 if (!emitHLSLConstructAggregate(BS.getType(), Elements, ElemIdx, E))
9337 return false;
9338 if (!this->emitFinishInitPop(E))
9339 return false;
9340 }
9341 }
9342
9343 for (const Record::Field &F : R->fields()) {
9344 if (F.isUnnamedBitField())
9345 continue;
9346
9347 QualType FieldType = F.Decl->getType();
9348 if (OptPrimType FieldT = F.T) {
9349 if (!loadAndCast(*FieldT, FieldType))
9350 return false;
9351 if (F.isBitField()) {
9352 if (!this->emitInitBitField(*FieldT, F.Offset, F.bitWidth(), E))
9353 return false;
9354 } else {
9355 if (!this->emitInitField(*FieldT, F.Offset, E))
9356 return false;
9357 }
9358 } else {
9359 if (!this->emitGetPtrField(F.Offset, E))
9360 return false;
9361 if (!emitHLSLConstructAggregate(FieldType, Elements, ElemIdx, E))
9362 return false;
9363 if (!this->emitPopPtr(E))
9364 return false;
9365 }
9366 }
9367 return true;
9368 }
9369
9370 return false;
9371}
9372
9373namespace clang {
9374namespace interp {
9375
9376template class Compiler<ByteCodeEmitter>;
9377template class Compiler<EvalEmitter>;
9378
9379} // namespace interp
9380} // 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:123
const LValueBase getLValueBase() const
Definition APValue.cpp:1011
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:629
ArrayRef< LValuePathEntry > getLValuePath() const
Definition APValue.cpp:1031
APSInt & getInt()
Definition APValue.h:511
APValue & getStructField(unsigned i)
Definition APValue.h:674
const FieldDecl * getUnionField() const
Definition APValue.h:695
unsigned getStructNumFields() const
Definition APValue.h:661
APValue & getStructVirtualBase(unsigned i)
Definition APValue.h:679
bool isArray() const
Definition APValue.h:496
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1101
unsigned getArrayInitializedElts() const
Definition APValue.h:648
bool isFloat() const
Definition APValue.h:489
unsigned getStructNumBases() const
Definition APValue.h:657
unsigned getStructNumVirtualBases() const
Definition APValue.h:665
bool hasLValuePath() const
Definition APValue.cpp:1026
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1094
APValue & getUnionValue()
Definition APValue.h:699
APValue & getArrayFiller()
Definition APValue.h:640
bool isLValue() const
Definition APValue.h:493
bool isIndeterminate() const
Definition APValue.h:485
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1108
bool isMemberPointer() const
Definition APValue.h:499
bool isInt() const
Definition APValue.h:488
unsigned getArraySize() const
Definition APValue.h:652
bool isUnion() const
Definition APValue.h:498
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:130
bool isStruct() const
Definition APValue.h:497
bool isNullPointer() const
Definition APValue.cpp:1047
APFloat & getFloat()
Definition APValue.h:525
APValue & getStructBase(unsigned i)
Definition APValue.h:669
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:239
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
const LangOptions & getLangOpts() const
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const VariableArrayType * getAsVariableArrayType(QualType T) const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4397
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4575
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4581
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4587
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition Expr.h:4594
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition Expr.h:6071
Represents a loop initializing the elements of an array.
Definition Expr.h:6018
llvm::APInt getArraySize() const
Definition Expr.h:6040
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:6033
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6038
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2765
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2794
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition ExprCXX.h:3010
uint64_t getValue() const
Definition ExprCXX.h:3058
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h: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:3526
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4082
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4215
Expr * getLHS() const
Definition Expr.h:4132
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4182
static bool isShiftOp(Opcode Opc)
Definition Expr.h:4170
static bool isCommaOp(Opcode Opc)
Definition Expr.h:4185
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4229
Expr * getRHS() const
Definition Expr.h:4134
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4159
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4218
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4223
Opcode getOpcode() const
Definition Expr.h:4127
static bool isBitwiseOp(Opcode Opc)
Definition Expr.h:4173
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6722
BreakStmt - This represents a break.
Definition Stmt.h:3147
Represents a C++2a __builtin_bit_cast(T, v) expression.
Definition ExprCXX.h:5529
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents binding an expression to a temporary.
Definition ExprCXX.h:1497
const Expr * getSubExpr() const
Definition ExprCXX.h:1519
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition ExprCXX.h:727
bool getValue() const
Definition ExprCXX.h:744
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1621
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1695
arg_range arguments()
Definition ExprCXX.h:1676
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1654
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1692
Represents a C++ constructor within a class.
Definition DeclCXX.h:2642
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:3049
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3069
Represents a C++ base or member initializer.
Definition DeclCXX.h:2407
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1274
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1381
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1138
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2630
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2669
bool isArrayForm() const
Definition ExprCXX.h:2656
bool isGlobalDelete() const
Definition ExprCXX.h:2655
Represents a C++ destructor within a class.
Definition DeclCXX.h:2907
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition ExprCXX.h:485
Represents the code generated for an expanded expansion statement.
Definition StmtCXX.h:1028
ArrayRef< Stmt * > getInstantiations() const
Definition StmtCXX.h:1069
ArrayRef< Stmt * > getPreambleStmts() const
Definition StmtCXX.h:1073
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:136
DeclStmt * getBeginStmt()
Definition StmtCXX.h:164
DeclStmt * getLoopVarStmt()
Definition StmtCXX.h:170
DeclStmt * getEndStmt()
Definition StmtCXX.h:167
DeclStmt * getRangeStmt()
Definition StmtCXX.h:163
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition ExprCXX.h:1755
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1792
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2293
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2751
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2730
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2895
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2359
bool isArray() const
Definition ExprCXX.h:2468
QualType getAllocatedType() const
Definition ExprCXX.h:2438
std::optional< Expr * > getArraySize()
This might return std::nullopt even if isArray() returns true, since there might not be an array size...
Definition ExprCXX.h:2473
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2507
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2498
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2463
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2537
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition ExprCXX.h:4362
bool getValue() const
Definition ExprCXX.h:4385
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:772
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5194
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5234
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition DeclCXX.h:1256
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1681
capture_const_range captures() const
Definition DeclCXX.h:1107
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1744
A C++ reinterpret_cast expression (C++ [expr.reinterpret.cast]).
Definition ExprCXX.h:530
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:290
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:308
An expression "T()" which creates an rvalue of a non-class type T.
Definition ExprCXX.h:2200
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition ExprCXX.h:804
Represents the this expression in C++.
Definition ExprCXX.h:1158
A C++ throw-expression (C++ [except.throw]).
Definition ExprCXX.h:1212
const Expr * getSubExpr() const
Definition ExprCXX.h:1232
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:70
CompoundStmt * getTryBlock()
Definition StmtCXX.h:101
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition ExprCXX.h:852
bool isTypeOperand() const
Definition ExprCXX.h:888
QualType getTypeOperand(const ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition ExprCXX.cpp:167
Expr * getExprOperand() const
Definition ExprCXX.h:899
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
Definition ExprCXX.cpp:135
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h:1072
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1118
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2987
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3191
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3170
Expr * getCallee()
Definition Expr.h:3134
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3178
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3181
arg_range arguments()
Definition Expr.h:3239
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1631
CaseStmt - Represent a case statement.
Definition Stmt.h:1932
Stmt * getSubStmt()
Definition Stmt.h:2045
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3720
path_iterator path_begin()
Definition Expr.h:3790
CastKind getCastKind() const
Definition Expr.h:3764
llvm::iterator_range< path_iterator > path()
Path through the class hierarchy taken by casts between base and derived classes (see implementation ...
Definition Expr.h:3807
const FieldDecl * getTargetUnionField() const
Definition Expr.h:3814
path_iterator path_end()
Definition Expr.h:3791
Expr * getSubExpr()
Definition Expr.h:3770
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:153
static CharUnits One()
Construct a CharUnits quantity of one.
Definition CharUnits.h:55
unsigned getValue() const
Definition Expr.h:1649
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4892
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4928
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
Complex values, per C99 6.2.5p11.
Definition TypeBase.h: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:4483
ContinueStmt - This represents a continue.
Definition Stmt.h:3131
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition Expr.h:4763
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4853
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1290
ValueDecl * getDecl()
Definition Expr.h:1358
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1643
decl_range decls()
Definition Stmt.h:1691
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInvalidDecl() const
Definition DeclBase.h:596
bool hasAttr() const
Definition DeclBase.h:585
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
Stmt * getSubStmt()
Definition Stmt.h:2093
InitListExpr * getUpdater() const
Definition Expr.h:5986
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2844
Stmt * getBody()
Definition Stmt.h:2869
Expr * getCond()
Definition Stmt.h:2862
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
Recursively visit a statement or expression, by dispatching to Traverse*() based on the argument's dy...
const Expr * getBase() const
Definition Expr.h:6631
Represents a reference to emded data.
Definition Expr.h:5179
ChildElementIter< false > begin()
Definition Expr.h:5285
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition ExprCXX.h:3714
This represents one expression.
Definition Expr.h:113
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:85
bool isGLValue() const
Definition Expr.h:288
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3111
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:247
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3119
bool isPRValue() const
Definition Expr.h:286
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:285
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3722
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition Expr.cpp:3286
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:480
QualType getType() const
Definition Expr.h:145
An expression trait intrinsic.
Definition ExprCXX.h:3083
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6660
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4592
Represents a member of a struct/union/class.
Definition Decl.h:3295
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3531
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1595
llvm::APFloat getValue() const
Definition Expr.h:1686
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2900
Stmt * getInit()
Definition Stmt.h:2915
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1120
Stmt * getBody()
Definition Stmt.h:2944
Expr * getInc()
Definition Stmt.h:2943
Expr * getCond()
Definition Stmt.h:2942
DeclStmt * getConditionVariableDeclStmt()
If this ForStmt has a condition variable, return the faux DeclStmt associated with the creation of th...
Definition Stmt.h:2930
const Expr * getSubExpr() const
Definition Expr.h:1082
Represents a function declaration or definition.
Definition Decl.h:2059
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2928
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3266
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4244
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4232
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3804
QualType getReturnType() const
Definition Decl.h:2976
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2504
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4368
bool isUsableAsGlobalAllocationFunctionInConstantEvaluation(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions described in i...
Definition Decl.cpp:3468
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2512
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3868
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3186
Declaration of a template function.
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, llvm::FoldingSetInsertToken &InsertToken)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition Expr.h:4967
Represents a C11 generic selection.
Definition Expr.h:6232
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition Expr.h:6518
IfStmt - This represents an if/then/else.
Definition Stmt.h:2271
Stmt * getThen()
Definition Stmt.h:2360
Stmt * getInit()
Definition Stmt.h:2421
bool isNonNegatedConsteval() const
Definition Stmt.h:2456
Expr * getCond()
Definition Stmt.h:2348
bool isNegatedConsteval() const
Definition Stmt.h:2460
Stmt * getElse()
Definition Stmt.h:2369
DeclStmt * getConditionVariableDeclStmt()
If this IfStmt has a condition variable, return the faux DeclStmt associated with the creation of tha...
Definition Stmt.h:2404
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1068
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1751
const Expr * getSubExpr() const
Definition Expr.h:1763
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6107
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3602
Describes an C or C++ initializer list.
Definition Expr.h:5352
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5455
ArrayRef< Expr * > inits() const
Definition Expr.h:5405
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1972
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2098
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1433
bool isCompatibleWith(ClangABI Version) const
Implicit declaration of a temporary that was materialized by a MaterializeTemporaryExpr and lifetime-...
Definition DeclCXX.h:3338
const Stmt * getNamedLoopOrSwitch() const
If this is a named break/continue, get the loop or switch statement that this targets.
Definition Stmt.cpp:1535
A global _GUID constant.
Definition DeclCXX.h:4451
APValue & getAsAPValue() const
Get the value of this MSGuidDecl as an APValue.
Definition DeclCXX.cpp:3931
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4973
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4998
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4990
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition ExprCXX.h:5023
LifetimeExtendedTemporaryDecl * getLifetimeExtendedTemporaryDecl()
Definition ExprCXX.h:5013
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3408
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3491
Expr * getBase() const
Definition Expr.h:3485
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h: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:3231
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp,...
Definition ExprObjC.h:219
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition ExprObjC.h:118
ObjCBoxedExpr - used for generalized expression boxing.
Definition ExprObjC.h:158
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition ExprObjC.h:341
ObjCEncodeExpr, used for @encode in Objective-C.
Definition ExprObjC.h:440
QualType getEncodedType() const
Definition ExprObjC.h:459
SourceLocation getAtLoc() const
Definition ExprObjC.h:454
bool isExpressibleAsConstantInitializer() const
Definition ExprObjC.h:67
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:83
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition Expr.h:2571
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2630
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2618
unsigned getNumComponents() const
Definition Expr.h:2626
Helper class for OffsetOfExpr.
Definition Expr.h:2465
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2523
@ Array
An index into an array.
Definition Expr.h:2470
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2519
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1198
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1248
Expr * getSelectedExpr() const
Definition ExprCXX.h:4692
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2226
const Expr * getSubExpr() const
Definition Expr.h:2243
Represents a parameter to a function.
Definition Decl.h:1820
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h: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:8523
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:8439
bool isConstant(const ASTContext &Ctx) const
Definition TypeBase.h:1098
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8512
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:4166
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4639
CompoundStmt * getSubStmt()
Definition Expr.h:4656
Stmt - This represents one statement.
Definition Stmt.h:85
StmtClass getStmtClass() const
Definition Stmt.h:1505
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1819
unsigned getLength() const
Definition Expr.h:1944
uint32_t getCodeUnit(size_t I) const
Return the code unit at the given position.
Definition Expr.h:1906
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1194
unsigned getCharByteWidth() const
Definition Expr.h:1946
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4717
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1905
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2521
Expr * getCond()
Definition Stmt.h:2584
Stmt * getBody()
Definition Stmt.h:2596
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1186
Stmt * getInit()
Definition Stmt.h:2601
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2652
DeclStmt * getConditionVariableDeclStmt()
If this SwitchStmt has a condition variable, return the faux DeclStmt associated with the creation of...
Definition Stmt.h:2635
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3852
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3953
bool isUnion() const
Definition Decl.h:4063
A template argument list.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
A type trait used in the implementation of various C++11 and Library TR1 trait templates.
Definition ExprCXX.h:2900
bool getBoolValue() const
Definition ExprCXX.h:2961
bool isStoredAsComparisonResult() const
Definition ExprCXX.h:2957
const APValue & getAPValue() const
Definition ExprCXX.h:2966
bool isStoredAsBoolean() const
Definition ExprCXX.h:2953
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9048
bool isBooleanType() const
Definition TypeBase.h:9185
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:3239
bool isIncompleteArrayType() const
Definition TypeBase.h:8783
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isNothrowT() const
Definition Type.cpp:3423
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:843
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2643
bool isArrayType() const
Definition TypeBase.h:8775
bool isFunctionPointerType() const
Definition TypeBase.h:8743
bool isConstantMatrixType() const
Definition TypeBase.h:8843
bool isPointerType() const
Definition TypeBase.h:8676
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9092
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9342
bool isReferenceType() const
Definition TypeBase.h:8700
bool isEnumeralType() const
Definition TypeBase.h:8807
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:883
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9170
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9017
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:8811
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9108
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9228
bool isMemberPointerType() const
Definition TypeBase.h:8757
bool isAtomicType() const
Definition TypeBase.h:8868
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isStdByteType() const
Definition Type.cpp:3442
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9328
bool isPointerOrReferenceType() const
Definition TypeBase.h:8680
bool isFunctionType() const
Definition TypeBase.h:8672
bool isVectorType() const
Definition TypeBase.h:8815
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2531
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2998
bool isFloatingType() const
Definition Type.cpp:2515
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9275
bool isRecordType() const
Definition TypeBase.h:8803
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2789
bool hasBooleanRepresentation() const
Determine whether this type has a boolean representation – i.e., it is a boolean type,...
Definition Type.cpp:2570
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3697
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2669
QualType getArgumentType() const
Definition Expr.h:2712
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2738
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2701
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2288
Expr * getSubExpr() const
Definition Expr.h:2329
Opcode getOpcode() const
Definition Expr.h:2324
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2342
Represents C++ using-directive.
Definition DeclCXX.h:3126
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
QualType getType() const
Definition Decl.h:724
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp: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:827
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:433
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1525
static llvm::RoundingMode getRoundingMode(FPOptions FPO)
constexpr bool isSignedType(PrimType T)
Definition PrimType.h:59
bool Div(InterpState &S, CodePtr OpPC)
1) Pops the RHS from the stack.
Definition Interp.h:778
constexpr bool isPtrType(PrimType T)
Definition PrimType.h:55
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition PrimType.h:213
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3228
constexpr bool isIntegerOrBoolType(PrimType T)
Definition PrimType.h:52
llvm::APFloat APFloat
Definition Floating.h:27
bool InitScope(InterpState &S, uint32_t I)
Definition Interp.h:2862
static void discard(InterpStack &Stk, PrimType T)
static bool isSideEffectFree(const Expr *E)
Check if E has side-effects.
Definition Compiler.cpp:44
llvm::APInt APInt
Definition FixedPoint.h:19
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1532
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:34
static std::optional< bool > getBoolValue(const Expr *E)
Definition Compiler.cpp:31
static bool Activate(InterpState &S)
Definition Interp.h:2308
bool Init(InterpState &S, CodePtr OpPC)
Definition Interp.h:2425
bool DefaultInit(InterpState &S, CodePtr OpPC, const CXXConstructorDecl *Ctor)
Definition Interp.cpp:2792
bool Mul(InterpState &S, CodePtr OpPC)
Definition Interp.h:487
size_t primSize(PrimType Type)
Returns the size of a primitive type in bytes.
Definition PrimType.cpp:24
bool Inc(InterpState &S, CodePtr OpPC, bool CanOverflow)
1) Pops a pointer from the stack 2) Load the value from the pointer 3) Writes the value increased by ...
Definition Interp.h:972
bool Add(InterpState &S, CodePtr OpPC)
Definition Interp.h:404
llvm::BitVector collectNonNullArgs(const FunctionDecl *F, ArrayRef< const Expr * > Args)
constexpr bool isIntegerType(PrimType T)
Definition PrimType.h:53
llvm::APSInt APSInt
Definition FixedPoint.h:20
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool hasSpecificAttr(const Container &container)
@ Success
Annotation was successful.
Definition Parser.h:65
@ Link
'link' clause, allowed on 'declare' construct.
DynamicRecursiveASTVisitorBase< true > ConstDynamicRecursiveASTVisitor
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
@ SD_Static
Static storage duration.
Definition Specifiers.h: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