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