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 if (!F)
4144 return false;
4145 assert(!F->hasRVO());
4146 assert(F->hasThisPointer());
4147
4148 if (!this->emitDupPtr(SourceInfo{}))
4149 return false;
4150
4151 // Forward all arguments of the current function (which should be a
4152 // constructor itself) to the inherited ctor.
4153 // This is necessary because the calling code has pushed the pointer
4154 // of the correct base for us already, but the arguments need
4155 // to come after.
4156 unsigned ParamIndex = 0;
4157 for (const ParmVarDecl *PD : Ctor->parameters()) {
4158 PrimType PT = this->classify(PD->getType()).value_or(PT_Ptr);
4159
4160 if (!this->emitGetParam(PT, ParamIndex, E))
4161 return false;
4162 ++ParamIndex;
4163 }
4164
4165 return this->emitCall(F, 0, E);
4166}
4167
4168// FIXME: This function has become rather unwieldy, especially
4169// the part where we initialize an array allocation of dynamic size.
4170template <class Emitter>
4172 assert(classifyPrim(E->getType()) == PT_Ptr);
4173 const Expr *Init = E->getInitializer();
4174 QualType ElementType = E->getAllocatedType();
4175 OptPrimType ElemT = classify(ElementType);
4176 unsigned PlacementArgs = E->getNumPlacementArgs();
4177 const FunctionDecl *OperatorNew = E->getOperatorNew();
4178 const Expr *PlacementDest = nullptr;
4179 bool IsNoThrow = false;
4180
4181 if (E->containsErrors())
4182 return false;
4183
4184 if (PlacementArgs != 0) {
4185 // FIXME: There is no restriction on this, but it's not clear that any
4186 // other form makes any sense. We get here for cases such as:
4187 //
4188 // new (std::align_val_t{N}) X(int)
4189 //
4190 // (which should presumably be valid only if N is a multiple of
4191 // alignof(int), and in any case can't be deallocated unless N is
4192 // alignof(X) and X has new-extended alignment).
4193 if (PlacementArgs == 1) {
4194 const Expr *Arg1 = E->getPlacementArg(0);
4195 if (Arg1->getType()->isNothrowT()) {
4196 if (!this->discard(Arg1))
4197 return false;
4198 IsNoThrow = true;
4199 } else {
4200 // Invalid unless we have C++26 or are in a std:: function.
4201 if (!this->emitInvalidNewDeleteExpr(E, E))
4202 return false;
4203
4204 // If we have a placement-new destination, we'll later use that instead
4205 // of allocating.
4206 if (OperatorNew->isReservedGlobalPlacementOperator())
4207 PlacementDest = Arg1;
4208 }
4209 } else {
4210 // Always invalid.
4211 return this->emitInvalid(E);
4212 }
4213 } else if (!OperatorNew
4214 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation())
4215 return this->emitInvalidNewDeleteExpr(E, E);
4216
4217 const Descriptor *Desc;
4218 if (!PlacementDest) {
4219 if (ElemT) {
4220 if (E->isArray())
4221 Desc = nullptr; // We're not going to use it in this case.
4222 else
4223 Desc = P.createDescriptor(E, *ElemT, /*SourceTy=*/nullptr,
4225 } else {
4226 Desc = P.createDescriptor(
4227 E, ElementType.getTypePtr(),
4228 E->isArray() ? std::nullopt : Descriptor::InlineDescMD,
4229 /*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false,
4230 /*IsVolatile=*/false, Init);
4231 }
4232 }
4233
4234 if (E->isArray()) {
4235 std::optional<const Expr *> ArraySizeExpr = E->getArraySize();
4236 if (!ArraySizeExpr)
4237 return false;
4238
4239 const Expr *Stripped = *ArraySizeExpr;
4240 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
4241 Stripped = ICE->getSubExpr())
4242 if (ICE->getCastKind() != CK_NoOp &&
4243 ICE->getCastKind() != CK_IntegralCast)
4244 break;
4245
4246 PrimType SizeT = classifyPrim(Stripped->getType());
4247
4248 // Save evaluated array size to a variable.
4249 unsigned ArrayLen =
4250 allocateLocalPrimitive(Stripped, SizeT, /*IsConst=*/false);
4251 if (!this->visit(Stripped))
4252 return false;
4253 if (!this->emitSetLocal(SizeT, ArrayLen, E))
4254 return false;
4255
4256 if (PlacementDest) {
4257 if (!this->visit(PlacementDest))
4258 return false;
4259 if (!this->emitGetLocal(SizeT, ArrayLen, E))
4260 return false;
4261 if (!this->emitCheckNewTypeMismatchArray(SizeT, E, E))
4262 return false;
4263 } else {
4264 if (!this->emitGetLocal(SizeT, ArrayLen, E))
4265 return false;
4266
4267 if (ElemT) {
4268 // N primitive elements.
4269 if (!this->emitAllocN(SizeT, *ElemT, E, IsNoThrow, E))
4270 return false;
4271 } else {
4272 // N Composite elements.
4273 if (!this->emitAllocCN(SizeT, Desc, IsNoThrow, E))
4274 return false;
4275 }
4276 }
4277
4278 if (Init) {
4279 QualType InitType = Init->getType();
4280 size_t StaticInitElems = 0;
4281 const Expr *DynamicInit = nullptr;
4282 OptPrimType ElemT;
4283
4284 if (const ConstantArrayType *CAT =
4285 Ctx.getASTContext().getAsConstantArrayType(InitType)) {
4286 StaticInitElems = CAT->getZExtSize();
4287 // Initialize the first S element from the initializer.
4288 if (!this->visitInitializer(Init))
4289 return false;
4290
4291 if (const auto *ILE = dyn_cast<InitListExpr>(Init)) {
4292 if (ILE->hasArrayFiller())
4293 DynamicInit = ILE->getArrayFiller();
4294 else if (StaticInitElems > 0 && isa<StringLiteral>(ILE->getInit(0)))
4295 ElemT = classifyPrim(CAT->getElementType());
4296 }
4297 }
4298
4299 // The initializer initializes a certain number of elements, S.
4300 // However, the complete number of elements, N, might be larger than that.
4301 // In this case, we need to get an initializer for the remaining elements.
4302 // There are three cases:
4303 // 1) For the form 'new Struct[n];', the initializer is a
4304 // CXXConstructExpr and its type is an IncompleteArrayType.
4305 // 2) For the form 'new Struct[n]{1,2,3}', the initializer is an
4306 // InitListExpr and the initializer for the remaining elements
4307 // is the array filler.
4308 // 3) StringLiterals don't have an array filler, so we need to zero
4309 // the remaining elements.
4310
4311 if (DynamicInit || ElemT || InitType->isIncompleteArrayType()) {
4312 const Function *CtorFunc = nullptr;
4313 if (const auto *CE = dyn_cast<CXXConstructExpr>(Init)) {
4314 CtorFunc = getFunction(CE->getConstructor());
4315 if (!CtorFunc)
4316 return false;
4317 } else if (!DynamicInit && !ElemT)
4318 DynamicInit = Init;
4319
4320 LabelTy EndLabel = this->getLabel();
4321 LabelTy StartLabel = this->getLabel();
4322
4323 // In the nothrow case, the alloc above might have returned nullptr.
4324 // Don't call any constructors that case.
4325 if (IsNoThrow) {
4326 if (!this->emitDupPtr(E))
4327 return false;
4328 if (!this->emitNullPtr(0, nullptr, E))
4329 return false;
4330 if (!this->emitEQPtr(E))
4331 return false;
4332 if (!this->jumpTrue(EndLabel, E))
4333 return false;
4334 }
4335
4336 // Create loop variables.
4337 unsigned Iter =
4338 allocateLocalPrimitive(Stripped, SizeT, /*IsConst=*/false);
4339 if (!this->emitConst(StaticInitElems, SizeT, E))
4340 return false;
4341 if (!this->emitSetLocal(SizeT, Iter, E))
4342 return false;
4343
4344 this->fallthrough(StartLabel);
4345 this->emitLabel(StartLabel);
4346 // Condition. Iter < ArrayLen?
4347 if (!this->emitGetLocal(SizeT, Iter, E))
4348 return false;
4349 if (!this->emitGetLocal(SizeT, ArrayLen, E))
4350 return false;
4351 if (!this->emitLT(SizeT, E))
4352 return false;
4353 if (!this->jumpFalse(EndLabel, E))
4354 return false;
4355
4356 // Pointer to the allocated array is already on the stack.
4357 if (!this->emitGetLocal(SizeT, Iter, E))
4358 return false;
4359 if (!this->emitArrayElemPtr(SizeT, E))
4360 return false;
4361
4362 if (isa_and_nonnull<ImplicitValueInitExpr>(DynamicInit) &&
4363 DynamicInit->getType()->isArrayType()) {
4364 QualType ElemType =
4365 DynamicInit->getType()->getAsArrayTypeUnsafe()->getElementType();
4366 if (OptPrimType InitT = classify(ElemType)) {
4367 if (!this->visitZeroInitializer(*InitT, ElemType, E))
4368 return false;
4369 if (!this->emitStorePop(*InitT, E))
4370 return false;
4371 } else {
4372 assert(ElemType->isArrayType());
4373 if (!this->visitZeroArrayInitializer(ElemType, E))
4374 return false;
4375 }
4376 } else if (DynamicInit) {
4377 if (OptPrimType InitT = classify(DynamicInit)) {
4378 if (!this->visit(DynamicInit))
4379 return false;
4380 if (!this->emitStorePop(*InitT, E))
4381 return false;
4382 } else {
4383 if (!this->visitInitializerPop(DynamicInit))
4384 return false;
4385 }
4386 } else if (ElemT) {
4387 if (!this->visitZeroInitializer(
4388 *ElemT, InitType->getAsArrayTypeUnsafe()->getElementType(),
4389 Init))
4390 return false;
4391 if (!this->emitStorePop(*ElemT, E))
4392 return false;
4393 } else {
4394 assert(CtorFunc);
4395 if (!this->emitCall(CtorFunc, 0, E))
4396 return false;
4397 }
4398
4399 // ++Iter;
4400 if (!this->emitGetPtrLocal(Iter, E))
4401 return false;
4402 if (!this->emitIncPop(SizeT, false, E))
4403 return false;
4404
4405 if (!this->jump(StartLabel, E))
4406 return false;
4407
4408 this->fallthrough(EndLabel);
4409 this->emitLabel(EndLabel);
4410 }
4411 }
4412 } else { // Non-array.
4413 if (PlacementDest) {
4414 if (!this->visit(PlacementDest))
4415 return false;
4416 if (!this->emitCheckNewTypeMismatch(E, E))
4417 return false;
4418
4419 } else {
4420 // Allocate just one element.
4421 if (!this->emitAlloc(Desc, E))
4422 return false;
4423 }
4424
4425 if (Init) {
4426 if (ElemT) {
4427 if (!this->visit(Init))
4428 return false;
4429
4430 if (!this->emitInit(*ElemT, E))
4431 return false;
4432 } else {
4433 // Composite.
4434 if (!this->visitInitializer(Init))
4435 return false;
4436 }
4437 }
4438 }
4439
4440 if (DiscardResult)
4441 return this->emitPopPtr(E);
4442
4443 return true;
4444}
4445
4446template <class Emitter>
4448 if (E->containsErrors())
4449 return false;
4450 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
4451
4452 if (!OperatorDelete->isUsableAsGlobalAllocationFunctionInConstantEvaluation())
4453 return this->emitInvalidNewDeleteExpr(E, E);
4454
4455 // Arg must be an lvalue.
4456 if (!this->visit(E->getArgument()))
4457 return false;
4458
4459 return this->emitFree(E->isArrayForm(), E->isGlobalDelete(), E);
4460}
4461
4462template <class Emitter>
4464 if (DiscardResult)
4465 return true;
4466
4467 const Function *Func = nullptr;
4468 if (const Function *F = Ctx.getOrCreateObjCBlock(E))
4469 Func = F;
4470
4471 if (!Func)
4472 return false;
4473 return this->emitGetFnPtr(Func, E);
4474}
4475
4476template <class Emitter>
4478 const Type *TypeInfoType = E->getType().getTypePtr();
4479
4480 auto canonType = [](const Type *T) {
4481 return T->getCanonicalTypeUnqualified().getTypePtr();
4482 };
4483
4484 if (!E->isPotentiallyEvaluated()) {
4485 if (DiscardResult)
4486 return true;
4487
4488 if (E->isTypeOperand())
4489 return this->emitGetTypeid(
4490 canonType(E->getTypeOperand(Ctx.getASTContext()).getTypePtr()),
4491 TypeInfoType, E);
4492
4493 return this->emitGetTypeid(
4494 canonType(E->getExprOperand()->getType().getTypePtr()), TypeInfoType,
4495 E);
4496 }
4497
4498 // Otherwise, we need to evaluate the expression operand.
4499 assert(E->getExprOperand());
4500 assert(E->getExprOperand()->isLValue());
4501
4502 if (!Ctx.getLangOpts().CPlusPlus20 && !this->emitDiagTypeid(E))
4503 return false;
4504
4505 if (!this->visit(E->getExprOperand()))
4506 return false;
4507
4508 if (!this->emitGetTypeidPtr(TypeInfoType, E))
4509 return false;
4510 if (DiscardResult)
4511 return this->emitPopPtr(E);
4512 return true;
4513}
4514
4515template <class Emitter>
4517 const ObjCDictionaryLiteral *E) {
4519 return this->emitDummyPtr(E, E);
4520 return this->emitError(E);
4521}
4522
4523template <class Emitter>
4526 return this->emitDummyPtr(E, E);
4527 return this->emitError(E);
4528}
4529
4530template <class Emitter>
4532 assert(Ctx.getLangOpts().CPlusPlus);
4533 return this->emitConstBool(E->getValue(), E);
4534}
4535
4536template <class Emitter>
4538 if (DiscardResult)
4539 return true;
4540 assert(!Initializing);
4541
4542 const MSGuidDecl *GuidDecl = E->getGuidDecl();
4543 const RecordDecl *RD = GuidDecl->getType()->getAsRecordDecl();
4544 assert(RD);
4545 // If the definiton of the result type is incomplete, just return a dummy.
4546 // If (and when) that is read from, we will fail, but not now.
4547 if (!RD->isCompleteDefinition())
4548 return this->emitDummyPtr(GuidDecl, E);
4549
4550 UnsignedOrNone GlobalIndex = P.getOrCreateGlobal(GuidDecl);
4551 if (!GlobalIndex)
4552 return false;
4553 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
4554 return false;
4555
4556 assert(this->getRecord(E->getType()));
4557
4558 const APValue &V = GuidDecl->getAsAPValue();
4559 if (V.getKind() == APValue::None)
4560 return true;
4561
4562 assert(V.isStruct());
4563 assert(V.getStructNumBases() == 0);
4564 if (!this->visitAPValueInitializer(V, E, E->getType()))
4565 return false;
4566
4567 return this->emitFinishInit(E);
4568}
4569
4570template <class Emitter>
4572 assert(classifyPrim(E->getType()) == PT_Bool);
4573 if (E->isValueDependent())
4574 return false;
4575 if (DiscardResult)
4576 return true;
4577 return this->emitConstBool(E->isSatisfied(), E);
4578}
4579
4580template <class Emitter>
4582 const ConceptSpecializationExpr *E) {
4583 assert(classifyPrim(E->getType()) == PT_Bool);
4584 if (DiscardResult)
4585 return true;
4586 return this->emitConstBool(E->isSatisfied(), E);
4587}
4588
4589template <class Emitter>
4594
4595template <class Emitter>
4597
4598 for (const Expr *SemE : E->semantics()) {
4599 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
4600 if (SemE == E->getResultExpr())
4601 return false;
4602
4603 if (OVE->isUnique())
4604 continue;
4605
4606 if (!this->discard(OVE))
4607 return false;
4608 } else if (SemE == E->getResultExpr()) {
4609 if (!this->delegate(SemE))
4610 return false;
4611 } else {
4612 if (!this->discard(SemE))
4613 return false;
4614 }
4615 }
4616 return true;
4617}
4618
4619template <class Emitter>
4623
4624template <class Emitter>
4626 return this->emitError(E);
4627}
4628
4629template <class Emitter>
4631 assert(E->getType()->isVoidPointerType());
4632 if (DiscardResult)
4633 return true;
4634
4635 return this->emitDummyPtr(E, E);
4636}
4637
4638template <class Emitter>
4639bool Compiler<Emitter>::emitVectorConversion(const Expr *Src, const Expr *E) {
4640 if (Src->containsErrors())
4641 return false;
4642
4643 const auto *VT = E->getType()->castAs<VectorType>();
4644 QualType ElemType = VT->getElementType();
4645 PrimType ElemT = classifyPrim(ElemType);
4646 QualType SrcType = Src->getType();
4647 PrimType SrcElemT = classifyVectorElementType(SrcType);
4648
4649 if (!Initializing) {
4650 UnsignedOrNone LocalIndex = allocateLocal(E);
4651 if (!LocalIndex)
4652 return false;
4653 if (!this->emitGetPtrLocal(*LocalIndex, E))
4654 return false;
4655 }
4656
4657 unsigned SrcOffset =
4658 this->allocateLocalPrimitive(Src, PT_Ptr, /*IsConst=*/true);
4659 if (!this->visit(Src))
4660 return false;
4661 if (!this->emitSetLocal(PT_Ptr, SrcOffset, E))
4662 return false;
4663
4664 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
4665 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
4666 return false;
4667 if (!this->emitArrayElemPop(SrcElemT, I, E))
4668 return false;
4669
4670 // Cast to the desired result element type.
4671 if (SrcElemT != ElemT) {
4672 if (!this->emitPrimCast(SrcElemT, ElemT, ElemType, E))
4673 return false;
4674 } else if (ElemType->isFloatingType() && SrcType != ElemType) {
4675 const auto *TargetSemantics = &Ctx.getFloatSemantics(ElemType);
4676 if (!this->emitCastFP(TargetSemantics, getRoundingMode(E), E))
4677 return false;
4678 }
4679 if (!this->emitInitElem(ElemT, I, E))
4680 return false;
4681 }
4682 return true;
4683}
4684
4685template <class Emitter>
4687 return emitVectorConversion(E->getSrcExpr(), E);
4688}
4689
4690template <class Emitter>
4692 // FIXME: Unary shuffle with mask not currently supported.
4693 if (E->getNumSubExprs() == 2)
4694 return this->emitInvalid(E);
4695
4696 assert(E->getNumSubExprs() > 2);
4697
4698 const Expr *Vecs[] = {E->getExpr(0), E->getExpr(1)};
4699 const VectorType *VT = Vecs[0]->getType()->castAs<VectorType>();
4700 PrimType ElemT = classifyPrim(VT->getElementType());
4701 unsigned NumInputElems = VT->getNumElements();
4702 unsigned NumOutputElems = E->getNumSubExprs() - 2;
4703 assert(NumOutputElems > 0);
4704
4705 if (!Initializing) {
4706 UnsignedOrNone LocalIndex = allocateLocal(E);
4707 if (!LocalIndex)
4708 return false;
4709 if (!this->emitGetPtrLocal(*LocalIndex, E))
4710 return false;
4711 }
4712
4713 // Save both input vectors to a local variable.
4714 unsigned VectorOffsets[2];
4715 for (unsigned I = 0; I != 2; ++I) {
4716 VectorOffsets[I] =
4717 this->allocateLocalPrimitive(Vecs[I], PT_Ptr, /*IsConst=*/true);
4718 if (!this->visit(Vecs[I]))
4719 return false;
4720 if (!this->emitSetLocal(PT_Ptr, VectorOffsets[I], E))
4721 return false;
4722 }
4723 for (unsigned I = 0; I != NumOutputElems; ++I) {
4724 APSInt ShuffleIndex = E->getShuffleMaskIdx(I);
4725 assert(ShuffleIndex >= -1);
4726 if (ShuffleIndex == -1)
4727 return this->emitInvalidShuffleVectorIndex(I, E);
4728
4729 assert(ShuffleIndex < (NumInputElems * 2));
4730 if (!this->emitGetLocal(PT_Ptr,
4731 VectorOffsets[ShuffleIndex >= NumInputElems], E))
4732 return false;
4733 unsigned InputVectorIndex = ShuffleIndex.getZExtValue() % NumInputElems;
4734 if (!this->emitArrayElemPop(ElemT, InputVectorIndex, E))
4735 return false;
4736
4737 if (!this->emitInitElem(ElemT, I, E))
4738 return false;
4739 }
4740
4741 if (DiscardResult)
4742 return this->emitPopPtr(E);
4743
4744 return true;
4745}
4746
4747template <class Emitter>
4749 const ExtVectorElementExpr *E) {
4750 const Expr *Base = E->getBase();
4751 assert(
4752 Base->getType()->isVectorType() ||
4753 Base->getType()->getAs<PointerType>()->getPointeeType()->isVectorType());
4754
4756 E->getEncodedElementAccess(Indices);
4757
4758 if (Indices.size() == 1) {
4759 if (!this->visit(Base))
4760 return false;
4761
4762 if (E->isGLValue()) {
4763 if (!this->emitConstUint32(Indices[0], E))
4764 return false;
4765 return this->emitArrayElemPtrPop(PT_Uint32, E);
4766 }
4767 // Else, also load the value.
4768 return this->emitArrayElemPop(classifyPrim(E->getType()), Indices[0], E);
4769 }
4770
4771 // Create a local variable for the base.
4772 unsigned BaseOffset = allocateLocalPrimitive(Base, PT_Ptr, /*IsConst=*/true);
4773 if (!this->visit(Base))
4774 return false;
4775 if (!this->emitSetLocal(PT_Ptr, BaseOffset, E))
4776 return false;
4777
4778 // Now the vector variable for the return value.
4779 if (!Initializing) {
4780 UnsignedOrNone ResultIndex = allocateLocal(E);
4781 if (!ResultIndex)
4782 return false;
4783 if (!this->emitGetPtrLocal(*ResultIndex, E))
4784 return false;
4785 }
4786
4787 assert(Indices.size() == E->getType()->getAs<VectorType>()->getNumElements());
4788
4789 PrimType ElemT =
4791 uint32_t DstIndex = 0;
4792 for (uint32_t I : Indices) {
4793 if (!this->emitGetLocal(PT_Ptr, BaseOffset, E))
4794 return false;
4795 if (!this->emitArrayElemPop(ElemT, I, E))
4796 return false;
4797 if (!this->emitInitElem(ElemT, DstIndex, E))
4798 return false;
4799 ++DstIndex;
4800 }
4801
4802 // Leave the result pointer on the stack.
4803 assert(!DiscardResult);
4804 return true;
4805}
4806
4807template <class Emitter>
4809 const Expr *SubExpr = E->getSubExpr();
4811 return this->discard(SubExpr) && this->emitInvalid(E);
4812
4813 if (DiscardResult)
4814 return true;
4815
4816 assert(classifyPrim(E) == PT_Ptr);
4817 return this->emitDummyPtr(E, E);
4818}
4819
4820template <class Emitter>
4822 const CXXStdInitializerListExpr *E) {
4823 const Expr *SubExpr = E->getSubExpr();
4825 Ctx.getASTContext().getAsConstantArrayType(SubExpr->getType());
4826 const Record *R = getRecord(E->getType());
4827 assert(Initializing);
4828 assert(SubExpr->isGLValue());
4829
4830 if (!this->visit(SubExpr))
4831 return false;
4832 if (!this->emitConstUint8(0, E))
4833 return false;
4834 if (!this->emitArrayElemPtrPopUint8(E))
4835 return false;
4836 if (!this->emitInitFieldPtr(R->getField(0u)->Offset, E))
4837 return false;
4838
4839 PrimType SecondFieldT = classifyPrim(R->getField(1u)->Decl->getType());
4840 if (isIntegerOrBoolType(SecondFieldT)) {
4841 if (!this->emitConst(ArrayType->getSize(), SecondFieldT, E))
4842 return false;
4843 return this->emitInitField(SecondFieldT, R->getField(1u)->Offset, E);
4844 }
4845 assert(SecondFieldT == PT_Ptr);
4846
4847 if (!this->emitGetFieldPtr(R->getField(0u)->Offset, E))
4848 return false;
4849 if (!this->emitExpandPtr(E))
4850 return false;
4851 if (!this->emitConst(ArrayType->getSize(), PT_Uint64, E))
4852 return false;
4853 if (!this->emitArrayElemPtrPop(PT_Uint64, E))
4854 return false;
4855 return this->emitInitFieldPtr(R->getField(1u)->Offset, E);
4856}
4857
4858template <class Emitter>
4860 LocalScope<Emitter> BS(this);
4861 llvm::SaveAndRestore StmtExprSAR(this->InStmtExpr, true);
4862
4863 const CompoundStmt *CS = E->getSubStmt();
4864 const Stmt *Result = CS->body_back();
4865 for (const Stmt *S : CS->body()) {
4866 if (S != Result) {
4867 if (!this->visitStmt(S))
4868 return false;
4869 continue;
4870 }
4871
4872 assert(S == Result);
4873 if (const Expr *ResultExpr = dyn_cast<Expr>(S))
4874 return this->delegate(ResultExpr);
4875 if (!this->visitStmt(S))
4876 return false;
4877 return this->emitUnsupported(E);
4878 }
4879
4880 return BS.destroyLocals();
4881}
4882
4883template <class Emitter> bool Compiler<Emitter>::discard(const Expr *E) {
4884 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/true,
4885 /*NewInitializing=*/false, /*ToLValue=*/false);
4886 return this->Visit(E);
4887}
4888
4889template <class Emitter> bool Compiler<Emitter>::delegate(const Expr *E) {
4890 // We're basically doing:
4891 // OptionScope<Emitter> Scope(this, DicardResult, Initializing, ToLValue);
4892 // but that's unnecessary of course.
4893 return this->Visit(E);
4894}
4895
4897 if (const auto *PE = dyn_cast<ParenExpr>(E))
4898 return stripCheckedDerivedToBaseCasts(PE->getSubExpr());
4899
4900 if (const auto *CE = dyn_cast<CastExpr>(E);
4901 CE &&
4902 (CE->getCastKind() == CK_DerivedToBase || CE->getCastKind() == CK_NoOp))
4903 return stripCheckedDerivedToBaseCasts(CE->getSubExpr());
4904
4905 return E;
4906}
4907
4908static const Expr *stripDerivedToBaseCasts(const Expr *E) {
4909 if (const auto *PE = dyn_cast<ParenExpr>(E))
4910 return stripDerivedToBaseCasts(PE->getSubExpr());
4911
4912 if (const auto *CE = dyn_cast<CastExpr>(E);
4913 CE && (CE->getCastKind() == CK_DerivedToBase ||
4914 CE->getCastKind() == CK_UncheckedDerivedToBase ||
4915 CE->getCastKind() == CK_NoOp))
4916 return stripDerivedToBaseCasts(CE->getSubExpr());
4917
4918 return E;
4919}
4920
4921template <class Emitter> bool Compiler<Emitter>::visit(const Expr *E) {
4922 if (E->getType().isNull())
4923 return false;
4924
4925 if (E->getType()->isVoidType())
4926 return this->discard(E);
4927
4928 // Create local variable to hold the return value.
4929 if (!E->isGLValue() && !canClassify(E->getType())) {
4930 UnsignedOrNone LocalIndex = allocateLocal(
4932 if (!LocalIndex)
4933 return false;
4934
4935 if (!this->emitGetPtrLocal(*LocalIndex, E))
4936 return false;
4937 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
4938 return this->visitInitializer(E);
4939 }
4940
4941 // Otherwise,we have a primitive return value, produce the value directly
4942 // and push it on the stack.
4943 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4944 /*NewInitializing=*/false, /*ToLValue=*/ToLValue);
4945 return this->Visit(E);
4946}
4947
4948template <class Emitter>
4950 assert(!canClassify(E->getType()));
4951
4952 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4953 /*NewInitializing=*/true, /*ToLValue=*/false);
4954 return this->Visit(E) && this->emitFinishInit(E);
4955}
4956
4957template <class Emitter>
4959 assert(!canClassify(E->getType()));
4960
4961 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4962 /*NewInitializing=*/true, /*ToLValue=*/false);
4963 return this->Visit(E) && this->emitFinishInitPop(E);
4964}
4965
4966template <class Emitter> bool Compiler<Emitter>::visitAsLValue(const Expr *E) {
4967 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4968 /*NewInitializing=*/false, /*ToLValue=*/true);
4969 return this->Visit(E);
4970}
4971
4972template <class Emitter> bool Compiler<Emitter>::visitBool(const Expr *E) {
4973 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4974 /*NewInitializing=*/false, /*ToLValue=*/ToLValue);
4975
4976 OptPrimType T = classify(E->getType());
4977 if (!T) {
4978 // Convert complex values to bool.
4979 if (E->getType()->isAnyComplexType()) {
4980 if (!this->visit(E))
4981 return false;
4982 return this->emitComplexBoolCast(E);
4983 }
4984 return false;
4985 }
4986
4987 if (!this->visit(E))
4988 return false;
4989
4990 if (T == PT_Bool)
4991 return true;
4992
4993 // Convert pointers to bool.
4994 if (T == PT_Ptr)
4995 return this->emitIsNonNullPtr(E);
4996
4997 // Or Floats.
4998 if (T == PT_Float)
4999 return this->emitCastFloatingIntegralBool(getFPOptions(E), E);
5000
5001 // Or anything else we can.
5002 return this->emitCast(*T, PT_Bool, E);
5003}
5004
5005template <class Emitter>
5006bool Compiler<Emitter>::visitZeroInitializer(PrimType T, QualType QT,
5007 const Expr *E) {
5008 if (const auto *AT = QT->getAs<AtomicType>())
5009 QT = AT->getValueType();
5010
5011 switch (T) {
5012 case PT_Bool:
5013 return this->emitZeroBool(E);
5014 case PT_Sint8:
5015 return this->emitZeroSint8(E);
5016 case PT_Uint8:
5017 return this->emitZeroUint8(E);
5018 case PT_Sint16:
5019 return this->emitZeroSint16(E);
5020 case PT_Uint16:
5021 return this->emitZeroUint16(E);
5022 case PT_Sint32:
5023 return this->emitZeroSint32(E);
5024 case PT_Uint32:
5025 return this->emitZeroUint32(E);
5026 case PT_Sint64:
5027 return this->emitZeroSint64(E);
5028 case PT_Uint64:
5029 return this->emitZeroUint64(E);
5030 case PT_IntAP:
5031 return this->emitZeroIntAP(Ctx.getBitWidth(QT), E);
5032 case PT_IntAPS:
5033 return this->emitZeroIntAPS(Ctx.getBitWidth(QT), E);
5034 case PT_Ptr:
5035 return this->emitNullPtr(Ctx.getASTContext().getTargetNullPointerValue(QT),
5036 nullptr, E);
5037 case PT_MemberPtr:
5038 return this->emitNullMemberPtr(0, nullptr, E);
5039 case PT_Float: {
5040 APFloat F = APFloat::getZero(Ctx.getFloatSemantics(QT));
5041 return this->emitFloat(F, E);
5042 }
5043 case PT_FixedPoint: {
5044 auto Sem = Ctx.getASTContext().getFixedPointSemantics(QT);
5045 return this->emitConstFixedPoint(FixedPoint::zero(Sem), E);
5046 }
5047 }
5048 llvm_unreachable("unknown primitive type");
5049}
5050
5051template <class Emitter>
5052bool Compiler<Emitter>::visitZeroRecordInitializer(const Record *R,
5053 const Expr *E) {
5054 assert(E);
5055 assert(R);
5056 // Fields
5057 for (const Record::Field &Field : R->fields()) {
5058 if (Field.isUnnamedBitField())
5059 continue;
5060
5061 const Descriptor *D = Field.Desc;
5062 if (D->isPrimitive()) {
5063 QualType QT = D->getType();
5064 PrimType T = D->getPrimType();
5065 if (!this->visitZeroInitializer(T, QT, E))
5066 return false;
5067 if (R->isUnion()) {
5068 if (!this->emitInitFieldActivate(T, Field.Offset, E))
5069 return false;
5070 break;
5071 }
5072 if (!this->emitInitField(T, Field.Offset, E))
5073 return false;
5074 continue;
5075 }
5076
5077 if (!this->emitGetPtrField(Field.Offset, E))
5078 return false;
5079
5080 if (D->isPrimitiveArray()) {
5081 QualType ET = D->getElemQualType();
5082 PrimType T = D->getPrimType();
5083 for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) {
5084 if (!this->visitZeroInitializer(T, ET, E))
5085 return false;
5086 if (!this->emitInitElem(T, I, E))
5087 return false;
5088 }
5089 } else if (D->isCompositeArray()) {
5090 // Can't be a vector or complex field.
5091 if (!this->visitZeroArrayInitializer(D->getType(), E))
5092 return false;
5093 } else if (D->isRecord()) {
5094 if (!this->visitZeroRecordInitializer(D->ElemRecord, E))
5095 return false;
5096 } else
5097 return false;
5098
5099 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5100 // object's first non-static named data member is zero-initialized
5101 if (R->isUnion()) {
5102 if (!this->emitFinishInitActivatePop(E))
5103 return false;
5104 break;
5105 }
5106 if (!this->emitFinishInitPop(E))
5107 return false;
5108 }
5109
5110 for (const Record::Base &B : R->bases()) {
5111 if (!this->emitGetPtrBase(B.Offset, E))
5112 return false;
5113 if (!this->visitZeroRecordInitializer(B.R, E))
5114 return false;
5115 if (!this->emitFinishInitPop(E))
5116 return false;
5117 }
5118
5119 // FIXME: Virtual bases.
5120
5121 return true;
5122}
5123
5124template <class Emitter>
5125bool Compiler<Emitter>::visitZeroArrayInitializer(QualType T, const Expr *E) {
5126 assert(T->isArrayType() || T->isAnyComplexType() || T->isVectorType());
5127 const ArrayType *AT = T->getAsArrayTypeUnsafe();
5128 QualType ElemType = AT->getElementType();
5129 size_t NumElems = cast<ConstantArrayType>(AT)->getZExtSize();
5130
5131 if (OptPrimType ElemT = classify(ElemType)) {
5132 for (size_t I = 0; I != NumElems; ++I) {
5133 if (!this->visitZeroInitializer(*ElemT, ElemType, E))
5134 return false;
5135 if (!this->emitInitElem(*ElemT, I, E))
5136 return false;
5137 }
5138 return true;
5139 }
5140 if (ElemType->isRecordType()) {
5141 const Record *R = getRecord(ElemType);
5142 if (!R)
5143 return false;
5144
5145 for (size_t I = 0; I != NumElems; ++I) {
5146 if (!this->emitConstUint32(I, E))
5147 return false;
5148 if (!this->emitArrayElemPtr(PT_Uint32, E))
5149 return false;
5150 if (!this->visitZeroRecordInitializer(R, E))
5151 return false;
5152 if (!this->emitPopPtr(E))
5153 return false;
5154 }
5155 return true;
5156 }
5157 if (ElemType->isArrayType()) {
5158 for (size_t I = 0; I != NumElems; ++I) {
5159 if (!this->emitConstUint32(I, E))
5160 return false;
5161 if (!this->emitArrayElemPtr(PT_Uint32, E))
5162 return false;
5163 if (!this->visitZeroArrayInitializer(ElemType, E))
5164 return false;
5165 if (!this->emitPopPtr(E))
5166 return false;
5167 }
5168 return true;
5169 }
5170
5171 return false;
5172}
5173
5174template <class Emitter>
5175bool Compiler<Emitter>::visitAssignment(const Expr *LHS, const Expr *RHS,
5176 const Expr *E) {
5177 if (!canClassify(E->getType()))
5178 return false;
5179
5180 bool NeedsFlip = !isSideEffectFree(RHS);
5181 if (!NeedsFlip) {
5182 if (!this->visit(LHS))
5183 return false;
5184 if (!this->visit(RHS))
5185 return false;
5186 } else {
5187 if (!this->visit(RHS))
5188 return false;
5189 if (!this->visit(LHS))
5190 return false;
5191 }
5192
5193 if (LHS->getType().isVolatileQualified())
5194 return this->emitInvalidStore(LHS->getType().getTypePtr(), E);
5195
5196 // We don't support assignments in C.
5197 if (!Ctx.getLangOpts().CPlusPlus && !this->emitInvalid(E))
5198 return false;
5199
5200 PrimType RHT = classifyPrim(RHS);
5201 bool Activates = refersToUnion(LHS);
5202 bool BitField = LHS->refersToBitField();
5203
5204 if (NeedsFlip && !this->emitFlip(PT_Ptr, RHT, E))
5205 return false;
5206
5207 if (DiscardResult) {
5208 if (BitField && Activates)
5209 return this->emitStoreBitFieldActivatePop(RHT, E);
5210 if (BitField)
5211 return this->emitStoreBitFieldPop(RHT, E);
5212 if (Activates)
5213 return this->emitStoreActivatePop(RHT, E);
5214 // Otherwise, regular non-activating store.
5215 return this->emitStorePop(RHT, E);
5216 }
5217
5218 auto maybeLoad = [&](bool Result) -> bool {
5219 if (!Result)
5220 return false;
5221 // Assignments aren't necessarily lvalues in C.
5222 // Load from them in that case.
5223 if (!E->isLValue())
5224 return this->emitLoadPop(RHT, E);
5225 return true;
5226 };
5227
5228 if (BitField && Activates)
5229 return maybeLoad(this->emitStoreBitFieldActivate(RHT, E));
5230 if (BitField)
5231 return maybeLoad(this->emitStoreBitField(RHT, E));
5232 if (Activates)
5233 return maybeLoad(this->emitStoreActivate(RHT, E));
5234 // Otherwise, regular non-activating store.
5235 return maybeLoad(this->emitStore(RHT, E));
5236}
5237
5238template <class Emitter>
5239template <typename T>
5240bool Compiler<Emitter>::emitConst(T Value, PrimType Ty, SourceInfo Info) {
5241 switch (Ty) {
5242 case PT_Sint8:
5243 return this->emitConstSint8(Value, Info);
5244 case PT_Uint8:
5245 return this->emitConstUint8(Value, Info);
5246 case PT_Sint16:
5247 return this->emitConstSint16(Value, Info);
5248 case PT_Uint16:
5249 return this->emitConstUint16(Value, Info);
5250 case PT_Sint32:
5251 return this->emitConstSint32(Value, Info);
5252 case PT_Uint32:
5253 return this->emitConstUint32(Value, Info);
5254 case PT_Sint64:
5255 return this->emitConstSint64(Value, Info);
5256 case PT_Uint64:
5257 return this->emitConstUint64(Value, Info);
5258 case PT_Bool:
5259 return this->emitConstBool(Value, Info);
5260 case PT_Ptr:
5261 case PT_MemberPtr:
5262 case PT_Float:
5263 case PT_IntAP:
5264 case PT_IntAPS:
5265 case PT_FixedPoint:
5266 llvm_unreachable("Invalid integral type");
5267 break;
5268 }
5269 llvm_unreachable("unknown primitive type");
5270}
5271
5272template <class Emitter>
5273template <typename T>
5274bool Compiler<Emitter>::emitConst(T Value, const Expr *E) {
5275 return this->emitConst(Value, classifyPrim(E->getType()), E);
5276}
5277
5278template <class Emitter>
5279bool Compiler<Emitter>::emitConst(const APSInt &Value, PrimType Ty,
5280 SourceInfo Info) {
5281 if (Ty == PT_IntAPS)
5282 return this->emitConstIntAPS(Value, Info);
5283 if (Ty == PT_IntAP)
5284 return this->emitConstIntAP(Value, Info);
5285
5286 if (Value.isSigned())
5287 return this->emitConst(Value.getSExtValue(), Ty, Info);
5288 return this->emitConst(Value.getZExtValue(), Ty, Info);
5289}
5290
5291template <class Emitter>
5292bool Compiler<Emitter>::emitConst(const APInt &Value, PrimType Ty,
5293 SourceInfo Info) {
5294 if (Ty == PT_IntAPS)
5295 return this->emitConstIntAPS(Value, Info);
5296 if (Ty == PT_IntAP)
5297 return this->emitConstIntAP(Value, Info);
5298
5299 if (isSignedType(Ty))
5300 return this->emitConst(Value.getSExtValue(), Ty, Info);
5301 return this->emitConst(Value.getZExtValue(), Ty, Info);
5302}
5303
5304template <class Emitter>
5305bool Compiler<Emitter>::emitConst(const APSInt &Value, const Expr *E) {
5306 return this->emitConst(Value, classifyPrim(E->getType()), E);
5307}
5308
5309template <class Emitter>
5311 bool IsConst,
5312 bool IsVolatile,
5313 ScopeKind SC) {
5314 // FIXME: There are cases where Src.is<Expr*>() is wrong, e.g.
5315 // (int){12} in C. Consider using Expr::isTemporaryObject() instead
5316 // or isa<MaterializeTemporaryExpr>().
5317 Descriptor *D = P.createDescriptor(Src, Ty, nullptr, Descriptor::InlineDescMD,
5318 IsConst, isa<const Expr *>(Src),
5319 /*IsMutable=*/false, IsVolatile);
5321 Scope::Local Local = this->createLocal(D);
5322 if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>()))
5323 Locals.insert({VD, Local});
5324 VarScope->addForScopeKind(Local, SC);
5325 return Local.Offset;
5326}
5327
5328template <class Emitter>
5330 ScopeKind SC) {
5331 const ValueDecl *Key = nullptr;
5332 const Expr *Init = nullptr;
5333 bool IsTemporary = false;
5334 if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) {
5335 Key = VD;
5336
5337 if (const auto *VarD = dyn_cast<VarDecl>(VD))
5338 Init = VarD->getInit();
5339 }
5340 if (auto *E = Src.dyn_cast<const Expr *>()) {
5341 IsTemporary = true;
5342 if (Ty.isNull())
5343 Ty = E->getType();
5344 }
5345
5346 Descriptor *D = P.createDescriptor(
5348 IsTemporary, /*IsMutable=*/false, /*IsVolatile=*/Ty.isVolatileQualified(),
5349 Init);
5350 if (!D)
5351 return std::nullopt;
5353
5354 Scope::Local Local = this->createLocal(D);
5355 if (Key)
5356 Locals.insert({Key, Local});
5357 VarScope->addForScopeKind(Local, SC);
5358 return Local.Offset;
5359}
5360
5361template <class Emitter>
5363 QualType Ty = E->getType();
5364 assert(!Ty->isRecordType());
5365
5366 Descriptor *D = P.createDescriptor(
5368 /*IsTemporary=*/true);
5369
5370 if (!D)
5371 return std::nullopt;
5372
5373 Scope::Local Local = this->createLocal(D);
5375 assert(S);
5376 // Attach to topmost scope.
5377 while (S->getParent())
5378 S = S->getParent();
5379 assert(S && !S->getParent());
5380 S->addLocal(Local);
5381 return Local.Offset;
5382}
5383
5384template <class Emitter>
5386 if (const PointerType *PT = dyn_cast<PointerType>(Ty))
5387 return PT->getPointeeType()->getAsCanonical<RecordType>();
5388 return Ty->getAsCanonical<RecordType>();
5389}
5390
5391template <class Emitter> Record *Compiler<Emitter>::getRecord(QualType Ty) {
5392 if (const auto *RecordTy = getRecordTy(Ty))
5393 return getRecord(RecordTy->getDecl()->getDefinitionOrSelf());
5394 return nullptr;
5395}
5396
5397template <class Emitter>
5399 return P.getOrCreateRecord(RD);
5400}
5401
5402template <class Emitter>
5404 return Ctx.getOrCreateFunction(FD);
5405}
5406
5407template <class Emitter>
5408bool Compiler<Emitter>::visitExpr(const Expr *E, bool DestroyToplevelScope) {
5410
5411 auto maybeDestroyLocals = [&]() -> bool {
5412 if (DestroyToplevelScope)
5413 return RootScope.destroyLocals() && this->emitCheckAllocations(E);
5414 return this->emitCheckAllocations(E);
5415 };
5416
5417 // Void expressions.
5418 if (E->getType()->isVoidType()) {
5419 if (!visit(E))
5420 return false;
5421 return this->emitRetVoid(E) && maybeDestroyLocals();
5422 }
5423
5424 // Expressions with a primitive return type.
5425 if (OptPrimType T = classify(E)) {
5426 if (!visit(E))
5427 return false;
5428
5429 return this->emitRet(*T, E) && maybeDestroyLocals();
5430 }
5431
5432 // Expressions with a composite return type.
5433 // For us, that means everything we don't
5434 // have a PrimType for.
5435 if (UnsignedOrNone LocalOffset = this->allocateLocal(E)) {
5436 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalOffset));
5437 if (!this->emitGetPtrLocal(*LocalOffset, E))
5438 return false;
5439
5440 if (!visitInitializer(E))
5441 return false;
5442 // We are destroying the locals AFTER the Ret op.
5443 // The Ret op needs to copy the (alive) values, but the
5444 // destructors may still turn the entire expression invalid.
5445 return this->emitRetValue(E) && maybeDestroyLocals();
5446 }
5447
5448 return maybeDestroyLocals() && false;
5449}
5450
5451template <class Emitter>
5453 bool DestroyToplevelScope) {
5454 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
5455 /*NewInitializing=*/false, /*ToLValue=*/true);
5456
5457 return this->visitExpr(E, DestroyToplevelScope);
5458}
5459
5460template <class Emitter>
5462
5463 auto R = this->visitVarDecl(VD, VD->getInit(), /*Toplevel=*/true);
5464
5465 if (R.notCreated())
5466 return R;
5467
5468 if (R)
5469 return true;
5470
5471 if (!R && Context::shouldBeGloballyIndexed(VD)) {
5472 if (auto GlobalIndex = P.getGlobal(VD)) {
5473 Block *GlobalBlock = P.getGlobal(*GlobalIndex);
5474 auto &GD = GlobalBlock->getBlockDesc<GlobalInlineDescriptor>();
5475
5477 GlobalBlock->invokeDtor();
5478 }
5479 }
5480
5481 return R;
5482}
5483
5484/// Toplevel visitDeclAndReturn().
5485/// We get here from evaluateAsInitializer().
5486/// We need to evaluate the initializer and return its value.
5487template <class Emitter>
5489 bool ConstantContext) {
5490 // We only create variables if we're evaluating in a constant context.
5491 // Otherwise, just evaluate the initializer and return it.
5492 if (!ConstantContext) {
5493 DeclScope<Emitter> LS(this, VD);
5494 if (!this->visit(Init))
5495 return false;
5496 return this->emitRet(classify(Init).value_or(PT_Ptr), VD) &&
5497 LS.destroyLocals() && this->emitCheckAllocations(VD);
5498 }
5499
5500 LocalScope<Emitter> VDScope(this);
5501 if (!this->visitVarDecl(VD, Init, /*Toplevel=*/true))
5502 return false;
5503
5504 OptPrimType VarT = classify(VD->getType());
5505 bool IsReference = VD->getType()->isReferenceType();
5507 auto GlobalIndex = P.getGlobal(VD);
5508 assert(GlobalIndex); // visitVarDecl() didn't return false.
5509 if (VarT) {
5510 if (!this->emitGetGlobalUnchecked(*VarT, *GlobalIndex, VD))
5511 return false;
5512 } else {
5513 if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
5514 return false;
5515 }
5516 } else {
5517 auto Local = Locals.find(VD);
5518 assert(Local != Locals.end()); // Same here.
5519 if (VarT) {
5520 if (IsReference) {
5521 if (!this->emitGetRefLocal(Local->second.Offset, VD))
5522 return false;
5523 } else if (!this->emitGetLocal(*VarT, Local->second.Offset, VD))
5524 return false;
5525 } else {
5526 if (!this->emitGetPtrLocal(Local->second.Offset, VD))
5527 return false;
5528 }
5529 }
5530
5531 // Return the value.
5532 if (!this->emitRet(VarT.value_or(PT_Ptr), VD)) {
5533 // If the Ret above failed and this is a global variable, mark it as
5534 // uninitialized, even everything else succeeded.
5536 auto GlobalIndex = P.getGlobal(VD);
5537 assert(GlobalIndex);
5538 Block *GlobalBlock = P.getGlobal(*GlobalIndex);
5539 auto &GD = GlobalBlock->getBlockDesc<GlobalInlineDescriptor>();
5540
5542 GlobalBlock->invokeDtor();
5543 }
5544 return false;
5545 }
5546
5547 return VDScope.destroyLocals() && this->emitCheckAllocations(VD);
5548}
5549
5550template <class Emitter>
5552 const Expr *Init,
5553 bool Toplevel) {
5554 QualType VarTy = VD->getType();
5555 // We don't know what to do with these, so just return false.
5556 if (VarTy.isNull())
5557 return false;
5558
5559 // This case is EvalEmitter-only. If we won't create any instructions for the
5560 // initializer anyway, don't bother creating the variable in the first place.
5561 if (!this->isActive())
5563
5564 OptPrimType VarT = classify(VD->getType());
5565
5566 if (Init && Init->isValueDependent())
5567 return false;
5568
5570 auto checkDecl = [&]() -> bool {
5571 bool NeedsOp = !Toplevel && VD->isLocalVarDecl() && VD->isStaticLocal();
5572 return !NeedsOp || this->emitCheckDecl(VD, VD);
5573 };
5574
5576 UnsignedOrNone GlobalIndex = P.getGlobal(VD);
5577 if (GlobalIndex) {
5578 // The global was previously created but the initializer failed.
5579 if (!P.getGlobal(*GlobalIndex)->isInitialized())
5580 return false;
5581 // We've already seen and initialized this global.
5582 if (P.isGlobalInitialized(*GlobalIndex))
5583 return checkDecl();
5584 // The previous attempt at initialization might've been unsuccessful,
5585 // so let's try this one.
5586 } else if ((GlobalIndex =
5587 P.createGlobal(VD, Init, VariablesAreConstexprUnknown))) {
5588 } else {
5589 return false;
5590 }
5591 if (!Init)
5592 return true;
5593
5594 if (!checkDecl())
5595 return false;
5596
5597 if (VarT) {
5598 if (!this->visit(Init))
5599 return false;
5600
5601 return this->emitInitGlobal(*VarT, *GlobalIndex, VD);
5602 }
5603
5604 if (!this->emitGetPtrGlobal(*GlobalIndex, Init))
5605 return false;
5606
5607 if (!this->emitStartInit(Init))
5608 return false;
5609
5610 if (!visitInitializer(Init))
5611 return false;
5612
5613 if (!this->emitEndInit(Init))
5614 return false;
5615
5616 return this->emitFinishInitGlobal(Init);
5617 }
5618 // Local variables.
5620
5621 if (VarT) {
5622 unsigned Offset = this->allocateLocalPrimitive(
5623 VD, *VarT, VarTy.isConstQualified(), VarTy.isVolatileQualified(),
5625
5626 if (!Init || Init->getType()->isVoidType())
5627 return true;
5628
5629 // If this is a toplevel declaration, create a scope for the
5630 // initializer.
5631 if (Toplevel) {
5633 if (!this->visit(Init))
5634 return false;
5635 return this->emitSetLocal(*VarT, Offset, VD) && Scope.destroyLocals();
5636 }
5637 if (!this->visit(Init))
5638 return false;
5639
5640 if (VarTy->isReferenceType()) {
5641 // [C++26][decl.ref]
5642 // The object designated by such a glvalue can be outside its lifetime
5643 // Because a null pointer value or a pointer past the end of an object
5644 // does not point to an object, a reference in a well-defined program
5645 // cannot refer to such things;
5646 assert(classifyPrim(VarTy) == PT_Ptr);
5647 if (!this->emitCheckRefInit(Init))
5648 return false;
5649 }
5650
5651 return this->emitSetLocal(*VarT, Offset, VD);
5652 }
5653 // Local composite variables.
5654 if (UnsignedOrNone Offset =
5655 this->allocateLocal(VD, VarTy, ScopeKind::Block)) {
5656 if (!Init)
5657 return true;
5658
5659 if (!this->emitGetPtrLocal(*Offset, Init))
5660 return false;
5661
5662 return visitInitializerPop(Init);
5663 }
5664 return false;
5665}
5666
5667template <class Emitter>
5669 assert(!canClassify(VD->getType()));
5670
5672 // Create a local variable to use as the instance.
5673 QualType Ty = VD->getType();
5674 Descriptor *D =
5675 P.createDescriptor(VD, Ty.getTypePtr(), Descriptor::InlineDescMD,
5676 /*IsConst=*/Ty.isConstQualified(),
5677 /*IsTemporary=*/false, /*IsMutable=*/false,
5678 /*IsVolatile=*/Ty.isVolatileQualified(), nullptr);
5679 if (!D)
5680 return false;
5681
5682 // FIXME: Would be nice if we didn't allocate the descriptor at all in this
5683 // case.
5684 if (D->hasTrivialDtor())
5685 return true;
5686
5687 Scope::Local Local = this->createLocal(D);
5688 Locals.insert({VD, Local});
5689 VarScope->addForScopeKind(Local, ScopeKind::Block);
5690
5691 if (!this->emitGetPtrLocal(Local.Offset, VD))
5692 return false;
5693
5694 if (!this->visitAPValueInitializer(Value, VD, Ty))
5695 return false;
5696
5697 return this->emitDestructionPop(D, VD);
5698}
5699
5701public:
5703 explicit ParamFinder() {}
5704
5705 bool VisitDeclRefExpr(const DeclRefExpr *E) override {
5706 if (const auto *P = dyn_cast<ParmVarDecl>(E->getDecl()))
5707 FoundParams.insert(P);
5708 return true;
5709 }
5710};
5711
5712/// Evaluate the \p Condition as if it was in the body of \p Callee.
5713/// Specifically, all the parameters of the callee are available to use
5714/// for the condition, and their values are given by \p Args (and \p This).
5715///
5716// Since this is a somewhat niche feature, we're abusing a few other mechanisms
5717// to implement this.
5718//
5719// We don't create an actual function frame but instead register the parameters
5720// as local variables.
5721//
5722// So we evaluate something like:
5723//
5724// bool thisfunc() {
5725// auto Arg0 = Args[0];
5726// ...
5727// return Condition;
5728// }
5729//
5730template <class Emitter>
5733 const Expr *This,
5734 const Expr *Condition) {
5735 // Instead of evaluating all parameters and trying to ignore failure,
5736 // we collect all the parameters used in the condition and only evaluate
5737 // those. Note that we still ignore failure in the loop below because the
5738 // failure might be inconsequential in the end,
5739 // e.g. in the case of `true || x`.
5740 ParamFinder PF;
5742
5743 LocalScope<Emitter> ArgScope(this);
5744 for (const ParmVarDecl *PVD : PF.FoundParams) {
5745 unsigned ParamIndex = 0;
5746 for (const ParmVarDecl *P : Callee->parameters()) {
5747 if (P == PVD)
5748 break;
5749 ++ParamIndex;
5750 }
5751
5752 const Expr *Arg = Args[ParamIndex];
5753 const ParmVarDecl *Param = Callee->getParamDecl(ParamIndex);
5754 if (OptPrimType ParamT = classify(Param->getType())) {
5755 unsigned ArgOffset =
5756 allocateLocalPrimitive(Param, *ParamT, /*IsConst=*/true);
5757 if (!this->visit(Arg))
5758 continue;
5759 if (!this->emitSetLocal(*ParamT, ArgOffset, Arg))
5760 return false;
5761 } else {
5762 UnsignedOrNone ArgOffset = this->allocateLocal(Param, Param->getType());
5763 if (!ArgOffset)
5764 return false;
5765 if (!this->emitGetPtrLocal(*ArgOffset, Arg))
5766 return false;
5767 if (!this->visitInitializerPop(Arg))
5768 continue;
5769 }
5770 }
5771
5772 if (This) {
5773 // We abuse the init stack for this and tell it to use
5774 // either a local variable or another decl for the This pointer.
5775 this->InitStackActive = true;
5776
5777 if (This->getType()->isPointerType()) {
5778 // Nothing to do here, the evaluation will fail if the instance
5779 // pointer is used.
5780 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(This)) {
5781 InitStack.push_back(InitLink::Decl(DRE->getDecl()));
5782 } else {
5783 assert(!canClassify(This->getType()));
5784 UnsignedOrNone ArgOffset = this->allocateLocal(This, This->getType());
5785 if (!ArgOffset)
5786 return false;
5787 if (!this->emitGetPtrLocal(*ArgOffset, This))
5788 return false;
5789 if (!this->visitInitializerPop(This))
5790 return false;
5791 this->InitStack.push_back(InitLink::Temp(*ArgOffset));
5792 }
5793 }
5794
5795 // Destruction of the argument values is part of the callee frame,
5796 // so we simply ignore them here.
5797 this->VarScope = nullptr;
5798
5799 LocalScope<Emitter> RetScope(this);
5800 if (!this->visit(Condition))
5801 return false;
5802 if (!RetScope.destroyLocals())
5803 return false;
5804
5805 // Result of the condition should be on the stack.
5806 return this->emitRet(PT_Bool, Condition);
5807}
5808
5809template <class Emitter>
5811 SourceInfo Info) {
5812 assert(!Val.isIndeterminate() && "Needs to be checked before");
5813 assert(!DiscardResult);
5814 if (Val.isInt())
5815 return this->emitConst(Val.getInt(), ValType, Info);
5816 if (Val.isFloat()) {
5817 APFloat F = Val.getFloat();
5818 return this->emitFloat(F, Info);
5819 }
5820
5821 if (Val.isMemberPointer()) {
5822 if (const ValueDecl *MemberDecl = Val.getMemberPointerDecl()) {
5823 if (!this->emitGetMemberPtr(MemberDecl, Info))
5824 return false;
5825
5826 bool IsDerived = Val.isMemberPointerToDerivedMember();
5827 // Apply the member pointer path.
5828 for (const CXXRecordDecl *PathEntry : Val.getMemberPointerPath()) {
5829 if (!this->emitCopyMemberPtrPath(PathEntry, IsDerived, Info))
5830 return false;
5831 }
5832
5833 return true;
5834 }
5835 return this->emitNullMemberPtr(0, nullptr, Info);
5836 }
5837
5838 if (Val.isLValue()) {
5839 if (Val.isNullPointer())
5840 return this->emitNull(ValType, 0, nullptr, Info);
5841
5844
5845 if (const Expr *BaseExpr = Base.dyn_cast<const Expr *>())
5846 return this->visit(BaseExpr);
5847 if (const auto *VD = Base.dyn_cast<const ValueDecl *>()) {
5848 if (!this->visitDeclRef(VD, Info.asExpr()))
5849 return false;
5850
5851 QualType EntryType = VD->getType();
5852 for (auto &Entry : Path) {
5853 if (EntryType->isArrayType()) {
5854 uint64_t Index = Entry.getAsArrayIndex();
5855 QualType ElemType =
5856 EntryType->getAsArrayTypeUnsafe()->getElementType();
5857 if (!this->emitConst(Index, PT_Uint64, Info))
5858 return false;
5859 if (!this->emitArrayElemPtrPop(PT_Uint64, Info))
5860 return false;
5861 EntryType = ElemType;
5862 } else {
5863 assert(EntryType->isRecordType());
5864 const Record *EntryRecord = getRecord(EntryType);
5865 if (!EntryRecord) {
5866 assert(false);
5867
5868 return false;
5869 }
5870
5871 const Decl *BaseOrMember = Entry.getAsBaseOrMember().getPointer();
5872 if (const auto *FD = dyn_cast<FieldDecl>(BaseOrMember)) {
5873 unsigned EntryOffset = EntryRecord->getField(FD)->Offset;
5874 if (!this->emitGetPtrFieldPop(EntryOffset, Info))
5875 return false;
5876 EntryType = FD->getType();
5877 } else {
5878 const auto *Base = cast<CXXRecordDecl>(BaseOrMember);
5879 unsigned BaseOffset = EntryRecord->getBase(Base)->Offset;
5880 if (!this->emitGetPtrBasePop(BaseOffset, /*NullOK=*/false, Info))
5881 return false;
5882 EntryType = Ctx.getASTContext().getCanonicalTagType(Base);
5883 }
5884 }
5885 }
5886
5887 return true;
5888 }
5889 }
5890
5891 return false;
5892}
5893
5894template <class Emitter>
5896 SourceInfo Info, QualType T) {
5897 if (Val.isStruct()) {
5898 const Record *R = this->getRecord(T);
5899 assert(R);
5900 for (unsigned I = 0, N = Val.getStructNumFields(); I != N; ++I) {
5901 const APValue &F = Val.getStructField(I);
5902 if (F.isIndeterminate())
5903 continue;
5904 const Record::Field *RF = R->getField(I);
5905 QualType FieldType = RF->Decl->getType();
5906
5907 // Fields.
5908 if (OptPrimType PT = classify(FieldType)) {
5909 if (!this->visitAPValue(F, *PT, Info))
5910 return false;
5911 if (!this->emitInitField(*PT, RF->Offset, Info))
5912 return false;
5913 } else {
5914 if (!this->emitGetPtrField(RF->Offset, Info))
5915 return false;
5916 if (!this->visitAPValueInitializer(F, Info, FieldType))
5917 return false;
5918 if (!this->emitFinishInitPop(Info))
5919 return false;
5920 }
5921 }
5922
5923 // Bases.
5924 for (unsigned I = 0, N = Val.getStructNumBases(); I != N; ++I) {
5925 // FIXME: APValue doesn't know about virtual bases.
5926 // We simply assume that if the APValue has more bases than the Record,
5927 // those additional bases must be virtual.
5928 if (I >= R->getNumBases())
5929 break;
5930 const APValue &B = Val.getStructBase(I);
5931 if (B.isIndeterminate())
5932 continue;
5933 const Record::Base *RB = R->getBase(I);
5934 QualType BaseType = Ctx.getASTContext().getCanonicalTagType(RB->Decl);
5935
5936 if (!this->emitGetPtrBase(RB->Offset, Info))
5937 return false;
5938 if (!this->visitAPValueInitializer(B, Info, BaseType))
5939 return false;
5940 if (!this->emitFinishInitPop(Info))
5941 return false;
5942 }
5943
5944 return true;
5945 }
5946 if (Val.isUnion()) {
5947 const FieldDecl *UnionField = Val.getUnionField();
5948 if (!UnionField)
5949 return true;
5950 const Record *R = this->getRecord(T);
5951 assert(R);
5952 const APValue &F = Val.getUnionValue();
5953 if (F.isIndeterminate())
5954 return true;
5955 const Record::Field *RF = R->getField(UnionField);
5956 QualType FieldType = RF->Decl->getType();
5957
5958 if (OptPrimType PT = classify(FieldType)) {
5959 if (!this->visitAPValue(F, *PT, Info))
5960 return false;
5961 if (RF->isBitField())
5962 return this->emitInitBitFieldActivate(*PT, RF->Offset, RF->bitWidth(),
5963 Info);
5964 return this->emitInitFieldActivate(*PT, RF->Offset, Info);
5965 }
5966
5967 if (!this->emitGetPtrField(RF->Offset, Info))
5968 return false;
5969 if (!this->emitActivate(Info))
5970 return false;
5971 if (!this->visitAPValueInitializer(F, Info, FieldType))
5972 return false;
5973 return this->emitPopPtr(Info);
5974 }
5975 if (Val.isArray()) {
5976 unsigned InitializedElems = Val.getArrayInitializedElts();
5977 const auto *ArrType = T->getAsArrayTypeUnsafe();
5978 QualType ElemType = ArrType->getElementType();
5979 OptPrimType ElemT = classify(ElemType);
5980
5981 for (unsigned A = 0, AN = Val.getArraySize(); A != AN; ++A) {
5982 const APValue &Elem = A >= InitializedElems
5983 ? Val.getArrayFiller()
5984 : Val.getArrayInitializedElt(A);
5985 if (Elem.isIndeterminate())
5986 continue;
5987
5988 if (ElemT) {
5989 if (!this->visitAPValue(Elem, *ElemT, Info))
5990 return false;
5991 if (!this->emitInitElem(*ElemT, A, Info))
5992 return false;
5993 } else {
5994 if (!this->emitConstUint32(A, Info))
5995 return false;
5996 if (!this->emitArrayElemPtrUint32(Info))
5997 return false;
5998 if (!this->visitAPValueInitializer(Elem, Info, ElemType))
5999 return false;
6000 if (!this->emitPopPtr(Info))
6001 return false;
6002 }
6003 }
6004 return true;
6005 }
6006 // TODO: Other types.
6007
6008 return false;
6009}
6010
6011template <class Emitter>
6013 unsigned BuiltinID) {
6014 if (BuiltinID == Builtin::BI__builtin_constant_p) {
6015 // Void argument is always invalid and harder to handle later.
6016 if (E->getArg(0)->getType()->isVoidType()) {
6017 if (DiscardResult)
6018 return true;
6019 return this->emitConst(0, E);
6020 }
6021
6022 if (!this->emitStartSpeculation(E))
6023 return false;
6024 LabelTy EndLabel = this->getLabel();
6025 if (!this->speculate(E, EndLabel))
6026 return false;
6027 if (!this->emitEndSpeculation(E))
6028 return false;
6029 this->fallthrough(EndLabel);
6030 if (DiscardResult)
6031 return this->emitPop(classifyPrim(E), E);
6032 return true;
6033 }
6034
6035 // For these, we're expected to ultimately return an APValue pointing
6036 // to the CallExpr. This is needed to get the correct codegen.
6037 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6038 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString ||
6039 BuiltinID == Builtin::BI__builtin_ptrauth_sign_constant ||
6040 BuiltinID == Builtin::BI__builtin_function_start) {
6041 if (DiscardResult)
6042 return true;
6043 return this->emitDummyPtr(E, E);
6044 }
6045
6047 OptPrimType ReturnT = classify(E);
6048
6049 // Non-primitive return type. Prepare storage.
6050 if (!Initializing && !ReturnT && !ReturnType->isVoidType()) {
6051 UnsignedOrNone LocalIndex = allocateLocal(E);
6052 if (!LocalIndex)
6053 return false;
6054 if (!this->emitGetPtrLocal(*LocalIndex, E))
6055 return false;
6056 }
6057
6058 // Prepare function arguments including special cases.
6059 switch (BuiltinID) {
6060 case Builtin::BI__builtin_object_size:
6061 case Builtin::BI__builtin_dynamic_object_size: {
6062 assert(E->getNumArgs() == 2);
6063 const Expr *Arg0 = E->getArg(0);
6064 if (Arg0->isGLValue()) {
6065 if (!this->visit(Arg0))
6066 return false;
6067
6068 } else {
6069 if (!this->visitAsLValue(Arg0))
6070 return false;
6071 }
6072 if (!this->visit(E->getArg(1)))
6073 return false;
6074
6075 } break;
6076 case Builtin::BI__assume:
6077 case Builtin::BI__builtin_assume:
6078 // Argument is not evaluated.
6079 break;
6080 case Builtin::BI__atomic_is_lock_free:
6081 case Builtin::BI__atomic_always_lock_free: {
6082 assert(E->getNumArgs() == 2);
6083 if (!this->visit(E->getArg(0)))
6084 return false;
6085 if (!this->visitAsLValue(E->getArg(1)))
6086 return false;
6087 } break;
6088
6089 default:
6090 if (!Context::isUnevaluatedBuiltin(BuiltinID)) {
6091 // Put arguments on the stack.
6092 for (const auto *Arg : E->arguments()) {
6093 if (!this->visit(Arg))
6094 return false;
6095 }
6096 }
6097 }
6098
6099 if (!this->emitCallBI(E, BuiltinID, E))
6100 return false;
6101
6102 if (DiscardResult && !ReturnType->isVoidType())
6103 return this->emitPop(ReturnT.value_or(PT_Ptr), E);
6104
6105 return true;
6106}
6107
6108template <class Emitter>
6110 if (E->containsErrors())
6111 return false;
6112 const FunctionDecl *FuncDecl = E->getDirectCallee();
6113
6114 if (FuncDecl) {
6115 if (unsigned BuiltinID = FuncDecl->getBuiltinID())
6116 return VisitBuiltinCallExpr(E, BuiltinID);
6117
6118 // Calls to replaceable operator new/operator delete.
6120 if (FuncDecl->getDeclName().isAnyOperatorNew())
6121 return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_new);
6122 assert(FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
6123 FuncDecl->getDeclName().getCXXOverloadedOperator() ==
6124 OO_Array_Delete);
6125 return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_delete);
6126 }
6127
6128 // Explicit calls to trivial destructors
6129 if (const auto *DD = dyn_cast<CXXDestructorDecl>(FuncDecl);
6130 DD && DD->isTrivial()) {
6131 const auto *MemberCall = cast<CXXMemberCallExpr>(E);
6132 if (!this->visit(MemberCall->getImplicitObjectArgument()))
6133 return false;
6134 return this->emitCheckDestruction(E) && this->emitEndLifetime(E) &&
6135 this->emitPopPtr(E);
6136 }
6137 }
6138
6139 LocalScope<Emitter> CallScope(this, ScopeKind::Call);
6140
6141 QualType ReturnType = E->getCallReturnType(Ctx.getASTContext());
6143 bool HasRVO = !ReturnType->isVoidType() && !T;
6144
6145 if (HasRVO) {
6146 if (DiscardResult) {
6147 // If we need to discard the return value but the function returns its
6148 // value via an RVO pointer, we need to create one such pointer just
6149 // for this call.
6150 if (UnsignedOrNone LocalIndex = allocateLocal(E)) {
6151 if (!this->emitGetPtrLocal(*LocalIndex, E))
6152 return false;
6153 }
6154 } else {
6155 // We need the result. Prepare a pointer to return or
6156 // dup the current one.
6157 if (!Initializing) {
6158 if (UnsignedOrNone LocalIndex = allocateLocal(E)) {
6159 if (!this->emitGetPtrLocal(*LocalIndex, E))
6160 return false;
6161 }
6162 }
6163 if (!this->emitDupPtr(E))
6164 return false;
6165 }
6166 }
6167
6169
6170 bool IsAssignmentOperatorCall = false;
6171 bool ActivateLHS = false;
6172 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
6173 OCE && OCE->isAssignmentOp()) {
6174 // Just like with regular assignments, we need to special-case assignment
6175 // operators here and evaluate the RHS (the second arg) before the LHS (the
6176 // first arg). We fix this by using a Flip op later.
6177 assert(Args.size() == 2);
6178 const CXXRecordDecl *LHSRecord = Args[0]->getType()->getAsCXXRecordDecl();
6179 ActivateLHS = LHSRecord && LHSRecord->hasTrivialDefaultConstructor();
6180 IsAssignmentOperatorCall = true;
6181 std::reverse(Args.begin(), Args.end());
6182 }
6183 // Calling a static operator will still
6184 // pass the instance, but we don't need it.
6185 // Discard it here.
6186 if (isa<CXXOperatorCallExpr>(E)) {
6187 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl);
6188 MD && MD->isStatic()) {
6189 if (!this->discard(E->getArg(0)))
6190 return false;
6191 // Drop first arg.
6192 Args.erase(Args.begin());
6193 }
6194 }
6195
6196 bool Devirtualized = false;
6197 UnsignedOrNone CalleeOffset = std::nullopt;
6198 // Add the (optional, implicit) This pointer.
6199 if (const auto *MC = dyn_cast<CXXMemberCallExpr>(E)) {
6200 if (!FuncDecl && classifyPrim(E->getCallee()) == PT_MemberPtr) {
6201 // If we end up creating a CallPtr op for this, we need the base of the
6202 // member pointer as the instance pointer, and later extract the function
6203 // decl as the function pointer.
6204 const Expr *Callee = E->getCallee();
6205 CalleeOffset =
6206 this->allocateLocalPrimitive(Callee, PT_MemberPtr, /*IsConst=*/true);
6207 if (!this->visit(Callee))
6208 return false;
6209 if (!this->emitSetLocal(PT_MemberPtr, *CalleeOffset, E))
6210 return false;
6211 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
6212 return false;
6213 if (!this->emitGetMemberPtrBase(E))
6214 return false;
6215 } else {
6216 const auto *InstancePtr = MC->getImplicitObjectArgument();
6217 if (isa_and_nonnull<CXXDestructorDecl>(CompilingFunction) ||
6218 isa_and_nonnull<CXXConstructorDecl>(CompilingFunction)) {
6219 const auto *Stripped = stripCheckedDerivedToBaseCasts(InstancePtr);
6220 if (isa<CXXThisExpr>(Stripped)) {
6221 FuncDecl =
6222 cast<CXXMethodDecl>(FuncDecl)->getCorrespondingMethodInClass(
6223 Stripped->getType()->getPointeeType()->getAsCXXRecordDecl());
6224 Devirtualized = true;
6225 if (!this->visit(Stripped))
6226 return false;
6227 } else {
6228 if (!this->visit(InstancePtr))
6229 return false;
6230 }
6231 } else {
6232 if (!this->visit(InstancePtr))
6233 return false;
6234 }
6235 }
6236 } else if (const auto *PD =
6237 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee())) {
6238 if (!this->emitCheckPseudoDtor(E))
6239 return false;
6240 const Expr *Base = PD->getBase();
6241 // E.g. `using T = int; 0.~T();`.
6242 if (OptPrimType BaseT = classify(Base); !BaseT || BaseT != PT_Ptr)
6243 return this->discard(Base);
6244 if (!this->visit(Base))
6245 return false;
6246 return this->emitPseudoDtor(E);
6247 } else if (!FuncDecl) {
6248 const Expr *Callee = E->getCallee();
6249 CalleeOffset =
6250 this->allocateLocalPrimitive(Callee, PT_Ptr, /*IsConst=*/true);
6251 if (!this->visit(Callee))
6252 return false;
6253 if (!this->emitSetLocal(PT_Ptr, *CalleeOffset, E))
6254 return false;
6255 }
6256
6257 if (!this->visitCallArgs(Args, FuncDecl, ActivateLHS,
6259 return false;
6260
6261 // Undo the argument reversal we did earlier.
6262 if (IsAssignmentOperatorCall) {
6263 assert(Args.size() == 2);
6264 PrimType Arg1T = classify(Args[0]).value_or(PT_Ptr);
6265 PrimType Arg2T = classify(Args[1]).value_or(PT_Ptr);
6266 if (!this->emitFlip(Arg2T, Arg1T, E))
6267 return false;
6268 }
6269
6270 if (FuncDecl) {
6271 const Function *Func = getFunction(FuncDecl);
6272 if (!Func)
6273 return false;
6274
6275 // In error cases, the function may be called with fewer arguments than
6276 // parameters.
6277 if (E->getNumArgs() < Func->getNumWrittenParams())
6278 return false;
6279
6280 assert(HasRVO == Func->hasRVO());
6281
6282 bool HasQualifier = false;
6283 if (const auto *ME = dyn_cast<MemberExpr>(E->getCallee()))
6284 HasQualifier = ME->hasQualifier();
6285
6286 bool IsVirtual = false;
6287 if (const auto *MD = dyn_cast<CXXMethodDecl>(FuncDecl))
6288 IsVirtual = !Devirtualized && MD->isVirtual();
6289
6290 // In any case call the function. The return value will end up on the stack
6291 // and if the function has RVO, we already have the pointer on the stack to
6292 // write the result into.
6293 if (IsVirtual && !HasQualifier) {
6294 uint32_t VarArgSize = 0;
6295 unsigned NumParams =
6296 Func->getNumWrittenParams() +
6297 (isa<CXXOperatorCallExpr>(E) && Func->hasImplicitThisPointer());
6298 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
6299 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6300
6301 if (!this->emitCallVirt(Func, VarArgSize, E))
6302 return false;
6303 } else if (Func->isVariadic()) {
6304 uint32_t VarArgSize = 0;
6305 unsigned NumParams =
6306 Func->getNumWrittenParams() +
6307 (isa<CXXOperatorCallExpr>(E) && Func->hasImplicitThisPointer());
6308 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
6309 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6310 if (!this->emitCallVar(Func, VarArgSize, E))
6311 return false;
6312 } else {
6313 if (!this->emitCall(Func, 0, E))
6314 return false;
6315 }
6316 } else {
6317 // Indirect call. Visit the callee, which will leave a FunctionPointer on
6318 // the stack. Cleanup of the returned value if necessary will be done after
6319 // the function call completed.
6320
6321 // Sum the size of all args from the call expr.
6322 uint32_t ArgSize = 0;
6323 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
6324 ArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6325
6326 // Get the callee, either from a member pointer or function pointer saved in
6327 // CalleeOffset.
6328 if (isa<CXXMemberCallExpr>(E) && CalleeOffset) {
6329 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
6330 return false;
6331 if (!this->emitGetMemberPtrDecl(E))
6332 return false;
6333 } else {
6334 if (!this->emitGetLocal(PT_Ptr, *CalleeOffset, E))
6335 return false;
6336 }
6337 if (!this->emitCallPtr(ArgSize, E, E))
6338 return false;
6339 }
6340
6341 // Cleanup for discarded return values.
6342 if (DiscardResult && !ReturnType->isVoidType() && T)
6343 return this->emitPop(*T, E) && CallScope.destroyLocals();
6344
6345 return CallScope.destroyLocals();
6346}
6347
6348template <class Emitter>
6350 SourceLocScope<Emitter> SLS(this, E);
6351
6352 return this->delegate(E->getExpr());
6353}
6354
6355template <class Emitter>
6357 SourceLocScope<Emitter> SLS(this, E);
6358
6359 return this->delegate(E->getExpr());
6360}
6361
6362template <class Emitter>
6364 if (DiscardResult)
6365 return true;
6366
6367 return this->emitConstBool(E->getValue(), E);
6368}
6369
6370template <class Emitter>
6372 const CXXNullPtrLiteralExpr *E) {
6373 if (DiscardResult)
6374 return true;
6375
6376 uint64_t Val = Ctx.getASTContext().getTargetNullPointerValue(E->getType());
6377 return this->emitNullPtr(Val, nullptr, E);
6378}
6379
6380template <class Emitter>
6382 if (DiscardResult)
6383 return true;
6384
6385 assert(E->getType()->isIntegerType());
6386
6387 PrimType T = classifyPrim(E->getType());
6388 return this->emitZero(T, E);
6389}
6390
6391template <class Emitter>
6393 if (DiscardResult)
6394 return true;
6395
6396 if constexpr (!std::is_same_v<Emitter, EvalEmitter>) {
6397 if (this->LambdaThisCapture.Offset > 0) {
6398 if (this->LambdaThisCapture.IsPtr)
6399 return this->emitGetThisFieldPtr(this->LambdaThisCapture.Offset, E);
6400 return this->emitGetPtrThisField(this->LambdaThisCapture.Offset, E);
6401 }
6402 }
6403
6404 // In some circumstances, the 'this' pointer does not actually refer to the
6405 // instance pointer of the current function frame, but e.g. to the declaration
6406 // currently being initialized. Here we emit the necessary instruction(s) for
6407 // this scenario.
6408 if (!InitStackActive || InitStack.empty())
6409 return this->emitThis(E);
6410
6411 // If our init stack is, for example:
6412 // 0 Stack: 3 (decl)
6413 // 1 Stack: 6 (init list)
6414 // 2 Stack: 1 (field)
6415 // 3 Stack: 6 (init list)
6416 // 4 Stack: 1 (field)
6417 //
6418 // We want to find the LAST element in it that's an init list,
6419 // which is marked with the K_InitList marker. The index right
6420 // before that points to an init list. We need to find the
6421 // elements before the K_InitList element that point to a base
6422 // (e.g. a decl or This), optionally followed by field, elem, etc.
6423 // In the example above, we want to emit elements [0..2].
6424 unsigned StartIndex = 0;
6425 unsigned EndIndex = 0;
6426 // Find the init list.
6427 for (StartIndex = InitStack.size() - 1; StartIndex > 0; --StartIndex) {
6428 if (InitStack[StartIndex].Kind == InitLink::K_DIE) {
6429 EndIndex = StartIndex;
6430 --StartIndex;
6431 break;
6432 }
6433 }
6434
6435 // Walk backwards to find the base.
6436 for (; StartIndex > 0; --StartIndex) {
6437 if (InitStack[StartIndex].Kind == InitLink::K_InitList)
6438 continue;
6439
6440 if (InitStack[StartIndex].Kind != InitLink::K_Field &&
6441 InitStack[StartIndex].Kind != InitLink::K_Elem &&
6442 InitStack[StartIndex].Kind != InitLink::K_DIE)
6443 break;
6444 }
6445
6446 if (StartIndex == 0 && EndIndex == 0)
6447 EndIndex = InitStack.size() - 1;
6448
6449 // NOTE: This could be StartIndex < EndIndex, but we're also abusing the
6450 // InitStack mechanism in visitWithSubstitutions to have the This pointer
6451 // _just_ be a local variable.
6452 assert(StartIndex <= EndIndex);
6453
6454 // Emit the instructions.
6455 for (unsigned I = StartIndex; I != (EndIndex + 1); ++I) {
6456 if (InitStack[I].Kind == InitLink::K_InitList ||
6457 InitStack[I].Kind == InitLink::K_DIE)
6458 continue;
6459 if (!InitStack[I].template emit<Emitter>(this, E))
6460 return false;
6461 }
6462 return true;
6463}
6464
6465template <class Emitter> bool Compiler<Emitter>::visitStmt(const Stmt *S) {
6466 switch (S->getStmtClass()) {
6467 case Stmt::CompoundStmtClass:
6469 case Stmt::DeclStmtClass:
6470 return visitDeclStmt(cast<DeclStmt>(S), /*EvaluateConditionDecl=*/true);
6471 case Stmt::ReturnStmtClass:
6473 case Stmt::IfStmtClass:
6474 return visitIfStmt(cast<IfStmt>(S));
6475 case Stmt::WhileStmtClass:
6477 case Stmt::DoStmtClass:
6478 return visitDoStmt(cast<DoStmt>(S));
6479 case Stmt::ForStmtClass:
6480 return visitForStmt(cast<ForStmt>(S));
6481 case Stmt::CXXForRangeStmtClass:
6483 case Stmt::BreakStmtClass:
6485 case Stmt::ContinueStmtClass:
6487 case Stmt::SwitchStmtClass:
6489 case Stmt::CaseStmtClass:
6490 return visitCaseStmt(cast<CaseStmt>(S));
6491 case Stmt::DefaultStmtClass:
6493 case Stmt::AttributedStmtClass:
6495 case Stmt::CXXTryStmtClass:
6497 case Stmt::NullStmtClass:
6498 return true;
6499 // Always invalid statements.
6500 case Stmt::GCCAsmStmtClass:
6501 case Stmt::MSAsmStmtClass:
6502 case Stmt::GotoStmtClass:
6503 return this->emitInvalid(S);
6504 case Stmt::LabelStmtClass:
6505 return this->visitStmt(cast<LabelStmt>(S)->getSubStmt());
6506 case Stmt::CXXExpansionStmtInstantiationClass:
6509 default: {
6510 if (const auto *E = dyn_cast<Expr>(S))
6511 return this->discard(E);
6512 return false;
6513 }
6514 }
6515}
6516
6517template <class Emitter>
6520 for (const auto *InnerStmt : S->body())
6521 if (!visitStmt(InnerStmt))
6522 return false;
6523 return Scope.destroyLocals();
6524}
6525
6526template <class Emitter>
6527bool Compiler<Emitter>::maybeEmitDeferredVarInit(const VarDecl *VD) {
6528 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
6529 for (auto *BD : DD->flat_bindings())
6530 if (auto *KD = BD->getHoldingVar();
6531 KD && !this->visitVarDecl(KD, KD->getInit()))
6532 return false;
6533 }
6534 return true;
6535}
6536
6538 assert(FD);
6539 assert(FD->getParent()->isUnion());
6540 const CXXRecordDecl *CXXRD =
6542 return !CXXRD || CXXRD->hasTrivialDefaultConstructor();
6543}
6544
6545template <class Emitter> bool Compiler<Emitter>::refersToUnion(const Expr *E) {
6546 for (;;) {
6547 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
6548 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6549 FD && FD->getParent()->isUnion() && hasTrivialDefaultCtorParent(FD))
6550 return true;
6551 E = ME->getBase();
6552 continue;
6553 }
6554
6555 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6556 E = ASE->getBase()->IgnoreImplicit();
6557 continue;
6558 }
6559
6560 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
6561 ICE && (ICE->getCastKind() == CK_NoOp ||
6562 ICE->getCastKind() == CK_DerivedToBase ||
6563 ICE->getCastKind() == CK_UncheckedDerivedToBase)) {
6564 E = ICE->getSubExpr();
6565 continue;
6566 }
6567
6568 if (const auto *This = dyn_cast<CXXThisExpr>(E)) {
6569 const auto *ThisRecord =
6570 This->getType()->getPointeeType()->getAsRecordDecl();
6571 if (!ThisRecord->isUnion())
6572 return false;
6573 // Otherwise, always activate if we're in the ctor.
6574 if (const auto *Ctor =
6575 dyn_cast_if_present<CXXConstructorDecl>(CompilingFunction))
6576 return Ctor->getParent() == ThisRecord;
6577 return false;
6578 }
6579
6580 break;
6581 }
6582 return false;
6583}
6584
6585template <class Emitter>
6587 bool EvaluateConditionDecl) {
6588 for (const auto *D : DS->decls()) {
6591 continue;
6592
6593 if (const auto *ESD = dyn_cast<CXXExpansionStmtDecl>(D)) {
6594 assert(ESD->getInstantiations() && "not expanded?");
6595 if (!this->visitStmt(ESD->getInstantiations()))
6596 return false;
6597 continue;
6598 }
6599
6600 const auto *VD = dyn_cast<VarDecl>(D);
6601 if (!VD)
6602 return false;
6603 if (!this->visitVarDecl(VD, VD->getInit()))
6604 return false;
6605
6606 // Register decomposition decl holding vars.
6607 if (EvaluateConditionDecl && !this->maybeEmitDeferredVarInit(VD))
6608 return false;
6609 }
6610
6611 return true;
6612}
6613
6614template <class Emitter>
6616 if (this->InStmtExpr)
6617 return this->emitUnsupported(RS);
6618
6619 if (const Expr *RE = RS->getRetValue()) {
6620 LocalScope<Emitter> RetScope(this);
6621 if (ReturnType) {
6622 // Primitive types are simply returned.
6623 if (!this->visit(RE))
6624 return false;
6625 this->emitCleanup();
6626 return this->emitRet(*ReturnType, RS);
6627 }
6628
6629 if (RE->getType()->isVoidType()) {
6630 if (!this->visit(RE))
6631 return false;
6632 } else {
6633 if (RE->containsErrors())
6634 return false;
6635
6637 // RVO - construct the value in the return location.
6638 if (!this->emitRVOPtr(RE))
6639 return false;
6640 if (!this->visitInitializerPop(RE))
6641 return false;
6642
6643 this->emitCleanup();
6644 return this->emitRetVoid(RS);
6645 }
6646 }
6647
6648 // Void return.
6649 this->emitCleanup();
6650 return this->emitRetVoid(RS);
6651}
6652
6653template <class Emitter> bool Compiler<Emitter>::visitIfStmt(const IfStmt *IS) {
6654 LocalScope<Emitter> IfScope(this);
6655
6656 auto visitChildStmt = [&](const Stmt *S) -> bool {
6657 LocalScope<Emitter> SScope(this);
6658 if (!visitStmt(S))
6659 return false;
6660 return SScope.destroyLocals();
6661 };
6662
6663 if (auto *CondInit = IS->getInit()) {
6664 if (!visitStmt(CondInit))
6665 return false;
6666 }
6667
6668 if (const DeclStmt *CondDecl = IS->getConditionVariableDeclStmt()) {
6669 if (!visitDeclStmt(CondDecl))
6670 return false;
6671 }
6672
6673 // Save ourselves compiling some code and the jumps, etc. if the condition is
6674 // stataically known to be either true or false. We could look at more cases
6675 // here, but I think all the ones that actually happen are using a
6676 // ConstantExpr.
6677 if (std::optional<bool> BoolValue = getBoolValue(IS->getCond())) {
6678 if (*BoolValue)
6679 return visitChildStmt(IS->getThen());
6680 if (const Stmt *Else = IS->getElse())
6681 return visitChildStmt(Else);
6682 return true;
6683 }
6684
6685 // Otherwise, compile the condition.
6686 if (IS->isNonNegatedConsteval()) {
6687 if (!this->emitIsConstantContext(IS))
6688 return false;
6689 } else if (IS->isNegatedConsteval()) {
6690 if (!this->emitIsConstantContext(IS))
6691 return false;
6692 if (!this->emitInv(IS))
6693 return false;
6694 } else {
6696 if (!this->visitBool(IS->getCond()))
6697 return false;
6698 if (!CondScope.destroyLocals())
6699 return false;
6700 }
6701
6702 if (!this->maybeEmitDeferredVarInit(IS->getConditionVariable()))
6703 return false;
6704
6705 if (const Stmt *Else = IS->getElse()) {
6706 LabelTy LabelElse = this->getLabel();
6707 LabelTy LabelEnd = this->getLabel();
6708 if (!this->jumpFalse(LabelElse, IS))
6709 return false;
6710 if (!visitChildStmt(IS->getThen()))
6711 return false;
6712 if (!this->jump(LabelEnd, IS))
6713 return false;
6714 this->emitLabel(LabelElse);
6715 if (!visitChildStmt(Else))
6716 return false;
6717 this->emitLabel(LabelEnd);
6718 } else {
6719 LabelTy LabelEnd = this->getLabel();
6720 if (!this->jumpFalse(LabelEnd, IS))
6721 return false;
6722 if (!visitChildStmt(IS->getThen()))
6723 return false;
6724 this->emitLabel(LabelEnd);
6725 }
6726
6727 if (!IfScope.destroyLocals())
6728 return false;
6729
6730 return true;
6731}
6732
6733template <class Emitter>
6735 const Expr *Cond = S->getCond();
6736 const Stmt *Body = S->getBody();
6737
6738 LabelTy CondLabel = this->getLabel(); // Label before the condition.
6739 LabelTy EndLabel = this->getLabel(); // Label after the loop.
6740 LocalScope<Emitter> WholeLoopScope(this);
6741 LoopScope<Emitter> LS(this, S, EndLabel, CondLabel);
6742
6743 this->fallthrough(CondLabel);
6744 this->emitLabel(CondLabel);
6745
6746 // Start of the loop body {
6747 LocalScope<Emitter> CondScope(this);
6748
6749 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) {
6750 if (!visitDeclStmt(CondDecl))
6751 return false;
6752 }
6753
6754 if (!this->visitBool(Cond))
6755 return false;
6756
6757 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
6758 return false;
6759
6760 if (!this->jumpFalse(EndLabel, S))
6761 return false;
6762
6763 if (!this->visitStmt(Body))
6764 return false;
6765
6766 if (!CondScope.destroyLocals())
6767 return false;
6768 // } End of loop body.
6769
6770 if (!this->jump(CondLabel, S))
6771 return false;
6772 this->fallthrough(EndLabel);
6773 this->emitLabel(EndLabel);
6774
6775 return CondScope.destroyLocals() && WholeLoopScope.destroyLocals();
6776}
6777
6778template <class Emitter> bool Compiler<Emitter>::visitDoStmt(const DoStmt *S) {
6779 const Expr *Cond = S->getCond();
6780 const Stmt *Body = S->getBody();
6781
6782 LabelTy StartLabel = this->getLabel();
6783 LabelTy EndLabel = this->getLabel();
6784 LabelTy CondLabel = this->getLabel();
6785 LocalScope<Emitter> WholeLoopScope(this);
6786 LoopScope<Emitter> LS(this, S, EndLabel, CondLabel);
6787
6788 this->fallthrough(StartLabel);
6789 this->emitLabel(StartLabel);
6790
6791 {
6792 LocalScope<Emitter> CondScope(this);
6793 if (!this->visitStmt(Body))
6794 return false;
6795 this->fallthrough(CondLabel);
6796 this->emitLabel(CondLabel);
6797 if (!this->visitBool(Cond))
6798 return false;
6799
6800 if (!CondScope.destroyLocals())
6801 return false;
6802 }
6803 if (!this->jumpTrue(StartLabel, S))
6804 return false;
6805
6806 this->fallthrough(EndLabel);
6807 this->emitLabel(EndLabel);
6808 return WholeLoopScope.destroyLocals();
6809}
6810
6811template <class Emitter>
6813 // for (Init; Cond; Inc) { Body }
6814 const Stmt *Init = S->getInit();
6815 const Expr *Cond = S->getCond();
6816 const Expr *Inc = S->getInc();
6817 const Stmt *Body = S->getBody();
6818
6819 LabelTy EndLabel = this->getLabel();
6820 LabelTy CondLabel = this->getLabel();
6821 LabelTy IncLabel = this->getLabel();
6822
6823 LocalScope<Emitter> WholeLoopScope(this);
6824 if (Init && !this->visitStmt(Init))
6825 return false;
6826
6827 // Start of the loop body {
6828 this->fallthrough(CondLabel);
6829 this->emitLabel(CondLabel);
6830
6831 LocalScope<Emitter> CondScope(this);
6832 LoopScope<Emitter> LS(this, S, EndLabel, IncLabel);
6833 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) {
6834 if (!visitDeclStmt(CondDecl))
6835 return false;
6836 }
6837
6838 if (Cond) {
6839 if (!this->visitBool(Cond))
6840 return false;
6841 if (!this->jumpFalse(EndLabel, S))
6842 return false;
6843 }
6844 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
6845 return false;
6846
6847 if (Body && !this->visitStmt(Body))
6848 return false;
6849
6850 this->fallthrough(IncLabel);
6851 this->emitLabel(IncLabel);
6852 if (Inc && !this->discard(Inc))
6853 return false;
6854
6855 if (!CondScope.destroyLocals())
6856 return false;
6857 if (!this->jump(CondLabel, S))
6858 return false;
6859 // } End of loop body.
6860
6861 this->emitLabel(EndLabel);
6862 // If we jumped out of the loop above, we still need to clean up the condition
6863 // scope.
6864 return CondScope.destroyLocals() && WholeLoopScope.destroyLocals();
6865}
6866
6867template <class Emitter>
6869 const Stmt *Init = S->getInit();
6870 const Expr *Cond = S->getCond();
6871 const Expr *Inc = S->getInc();
6872 const Stmt *Body = S->getBody();
6873 const Stmt *BeginStmt = S->getBeginStmt();
6874 const Stmt *RangeStmt = S->getRangeStmt();
6875 const Stmt *EndStmt = S->getEndStmt();
6876
6877 LabelTy EndLabel = this->getLabel();
6878 LabelTy CondLabel = this->getLabel();
6879 LabelTy IncLabel = this->getLabel();
6880 LocalScope<Emitter> WholeLoopScope(this);
6881 LoopScope<Emitter> LS(this, S, EndLabel, IncLabel);
6882
6883 // Emit declarations needed in the loop.
6884 if (Init && !this->visitStmt(Init))
6885 return false;
6886 if (!this->visitStmt(RangeStmt))
6887 return false;
6888 if (!this->visitStmt(BeginStmt))
6889 return false;
6890 if (!this->visitStmt(EndStmt))
6891 return false;
6892
6893 // Now the condition as well as the loop variable assignment.
6894 this->fallthrough(CondLabel);
6895 this->emitLabel(CondLabel);
6896 if (!this->visitBool(Cond))
6897 return false;
6898 if (!this->jumpFalse(EndLabel, S))
6899 return false;
6900
6901 if (!this->visitDeclStmt(S->getLoopVarStmt(), /*EvaluateConditionDecl=*/true))
6902 return false;
6903
6904 // Body.
6905 {
6906 if (!this->visitStmt(Body))
6907 return false;
6908
6909 this->fallthrough(IncLabel);
6910 this->emitLabel(IncLabel);
6911 if (!this->discard(Inc))
6912 return false;
6913 }
6914
6915 if (!this->jump(CondLabel, S))
6916 return false;
6917
6918 this->fallthrough(EndLabel);
6919 this->emitLabel(EndLabel);
6920 return WholeLoopScope.destroyLocals();
6921}
6922
6923template <class Emitter>
6925 if (LabelInfoStack.empty())
6926 return false;
6927
6928 OptLabelTy TargetLabel = std::nullopt;
6929 const Stmt *TargetLoop = S->getNamedLoopOrSwitch();
6930 const VariableScope<Emitter> *BreakScope = nullptr;
6931
6932 if (!TargetLoop) {
6933 for (const auto &LI : llvm::reverse(LabelInfoStack)) {
6934 if (LI.BreakLabel) {
6935 TargetLabel = *LI.BreakLabel;
6936 BreakScope = LI.BreakOrContinueScope;
6937 break;
6938 }
6939 }
6940 } else {
6941 for (auto LI : LabelInfoStack) {
6942 if (LI.Name == TargetLoop) {
6943 TargetLabel = *LI.BreakLabel;
6944 BreakScope = LI.BreakOrContinueScope;
6945 break;
6946 }
6947 }
6948 }
6949
6950 // Faulty break statement (e.g. label redefined or named loops disabled).
6951 if (!TargetLabel)
6952 return false;
6953
6954 for (VariableScope<Emitter> *C = this->VarScope; C != BreakScope;
6955 C = C->getParent()) {
6956 if (!C->destroyLocals())
6957 return false;
6958 }
6959
6960 return this->jump(*TargetLabel, S);
6961}
6962
6963template <class Emitter>
6965 if (LabelInfoStack.empty())
6966 return false;
6967
6968 OptLabelTy TargetLabel = std::nullopt;
6969 const Stmt *TargetLoop = S->getNamedLoopOrSwitch();
6970 const VariableScope<Emitter> *ContinueScope = nullptr;
6971
6972 if (!TargetLoop) {
6973 for (const auto &LI : llvm::reverse(LabelInfoStack)) {
6974 if (LI.ContinueLabel) {
6975 TargetLabel = *LI.ContinueLabel;
6976 ContinueScope = LI.BreakOrContinueScope;
6977 break;
6978 }
6979 }
6980 } else {
6981 for (auto LI : LabelInfoStack) {
6982 if (LI.Name == TargetLoop) {
6983 TargetLabel = *LI.ContinueLabel;
6984 ContinueScope = LI.BreakOrContinueScope;
6985 break;
6986 }
6987 }
6988 }
6989 assert(TargetLabel);
6990
6991 for (VariableScope<Emitter> *C = VarScope; C != ContinueScope;
6992 C = C->getParent()) {
6993 if (!C->destroyLocals())
6994 return false;
6995 }
6996
6997 return this->jump(*TargetLabel, S);
6998}
6999
7000template <class Emitter>
7002 const Expr *Cond = S->getCond();
7003 if (Cond->containsErrors())
7004 return false;
7005
7006 PrimType CondT = this->classifyPrim(Cond->getType());
7007 LocalScope<Emitter> LS(this);
7008 llvm::SaveAndRestore StmtExprSAR(this->SwitchInStmtExpr, this->InStmtExpr);
7009
7010 LabelTy EndLabel = this->getLabel();
7011 UnsignedOrNone DefaultLabel = std::nullopt;
7012 unsigned CondVar =
7013 this->allocateLocalPrimitive(Cond, CondT, /*IsConst=*/true);
7014
7015 if (const auto *CondInit = S->getInit())
7016 if (!visitStmt(CondInit))
7017 return false;
7018
7019 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
7020 if (!visitDeclStmt(CondDecl))
7021 return false;
7022
7023 // Initialize condition variable.
7024 if (!this->visit(Cond))
7025 return false;
7026 if (!this->emitSetLocal(CondT, CondVar, S))
7027 return false;
7028
7029 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
7030 return false;
7031
7033 // Create labels and comparison ops for all case statements.
7034 for (const SwitchCase *SC = S->getSwitchCaseList(); SC;
7035 SC = SC->getNextSwitchCase()) {
7036 if (const auto *CS = dyn_cast<CaseStmt>(SC)) {
7037 CaseLabels[SC] = this->getLabel();
7038
7039 if (CS->caseStmtIsGNURange()) {
7040 LabelTy EndOfRangeCheck = this->getLabel();
7041 const Expr *Low = CS->getLHS();
7042 const Expr *High = CS->getRHS();
7043 if (Low->isValueDependent() || High->isValueDependent())
7044 return false;
7045
7046 if (!this->emitGetLocal(CondT, CondVar, CS))
7047 return false;
7048 if (!this->visit(Low))
7049 return false;
7050 PrimType LT = this->classifyPrim(Low->getType());
7051 if (!this->emitGE(LT, S))
7052 return false;
7053 if (!this->jumpFalse(EndOfRangeCheck, S))
7054 return false;
7055
7056 if (!this->emitGetLocal(CondT, CondVar, CS))
7057 return false;
7058 if (!this->visit(High))
7059 return false;
7060 PrimType HT = this->classifyPrim(High->getType());
7061 if (!this->emitLE(HT, S))
7062 return false;
7063 if (!this->jumpTrue(CaseLabels[CS], S))
7064 return false;
7065 this->emitLabel(EndOfRangeCheck);
7066 continue;
7067 }
7068
7069 const Expr *Value = CS->getLHS();
7070 if (Value->isValueDependent())
7071 return false;
7072 PrimType ValueT = this->classifyPrim(Value->getType());
7073
7074 // Compare the case statement's value to the switch condition.
7075 if (!this->emitGetLocal(CondT, CondVar, CS))
7076 return false;
7077 if (!this->visit(Value))
7078 return false;
7079
7080 // Compare and jump to the case label.
7081 if (!this->emitEQ(ValueT, S))
7082 return false;
7083 if (!this->jumpTrue(CaseLabels[CS], S))
7084 return false;
7085 } else {
7086 assert(!DefaultLabel);
7087 DefaultLabel = this->getLabel();
7088 }
7089 }
7090
7091 // If none of the conditions above were true, fall through to the default
7092 // statement or jump after the switch statement.
7093 if (DefaultLabel) {
7094 if (!this->jump(*DefaultLabel, S))
7095 return false;
7096 } else {
7097 if (!this->jump(EndLabel, S))
7098 return false;
7099 }
7100
7101 SwitchScope<Emitter> SS(this, S, std::move(CaseLabels), EndLabel,
7102 DefaultLabel);
7103 if (!this->visitStmt(S->getBody()))
7104 return false;
7105 this->fallthrough(EndLabel);
7106 this->emitLabel(EndLabel);
7107
7108 return LS.destroyLocals();
7109}
7110
7111template <class Emitter>
7113 this->fallthrough(CaseLabels[S]);
7114 this->emitLabel(CaseLabels[S]);
7115
7116 // We can't jump from an outer switch statement to a case label
7117 // that's inside a StmtExpr.
7118 if (this->InStmtExpr && !this->SwitchInStmtExpr)
7119 return this->emitUnsupported(S);
7120
7121 return this->visitStmt(S->getSubStmt());
7122}
7123
7124template <class Emitter>
7126 if (LabelInfoStack.empty())
7127 return false;
7128
7129 LabelTy DefaultLabel;
7130 for (const LabelInfo &LI : llvm::reverse(LabelInfoStack)) {
7131 if (LI.DefaultLabel) {
7132 DefaultLabel = *LI.DefaultLabel;
7133 break;
7134 }
7135 }
7136
7137 this->emitLabel(DefaultLabel);
7138 return this->visitStmt(S->getSubStmt());
7139}
7140
7141template <class Emitter>
7143 const Stmt *SubStmt = S->getSubStmt();
7144
7145 bool IsMSVCConstexprAttr = isa<ReturnStmt>(SubStmt) &&
7147
7148 if (IsMSVCConstexprAttr && !this->emitPushMSVCCE(S))
7149 return false;
7150
7151 if (this->Ctx.getLangOpts().CXXAssumptions &&
7152 !this->Ctx.getLangOpts().MSVCCompat) {
7153 for (const Attr *A : S->getAttrs()) {
7154 auto *AA = dyn_cast<CXXAssumeAttr>(A);
7155 if (!AA)
7156 continue;
7157
7158 assert(isa<NullStmt>(SubStmt));
7159
7160 const Expr *Assumption = AA->getAssumption();
7161 if (Assumption->isValueDependent())
7162 return false;
7163
7164 if (Assumption->HasSideEffects(this->Ctx.getASTContext()))
7165 continue;
7166
7167 // Evaluate assumption.
7168 if (!this->visitBool(Assumption))
7169 return false;
7170
7171 if (!this->emitAssume(Assumption))
7172 return false;
7173 }
7174 }
7175
7176 // Ignore other attributes.
7177 if (!this->visitStmt(SubStmt))
7178 return false;
7179
7180 if (IsMSVCConstexprAttr)
7181 return this->emitPopMSVCCE(S);
7182 return true;
7183}
7184
7185template <class Emitter>
7187 // Ignore all handlers.
7188 return this->visitStmt(S->getTryBlock());
7189}
7190
7191/// template for (auto x : {1, 2}) {}
7192///
7193/// This is not a loop from an AST perspective at all since it has already
7194/// been instantiated to a list of compound statements.
7195///
7196/// Since we can have control flow in those compound statements, we need to
7197/// handle it mostly like a loop though.
7198template <class Emitter>
7201 LocalScope<Emitter> WholeLoopScope(this, ScopeKind::Block);
7202
7203 for (const Stmt *PreambleStmt : S->getPreambleStmts()) {
7204 if (!this->visitDeclStmt(cast<DeclStmt>(PreambleStmt), true))
7205 return false;
7206 }
7207
7208 LabelTy EndLabel = this->getLabel();
7209 for (const Stmt *Instantiation : S->getInstantiations()) {
7210 LabelTy ContinueLabel = this->getLabel();
7211 LoopScope<Emitter> LS(this, S, EndLabel, ContinueLabel);
7212
7213 if (!this->visitStmt(Instantiation))
7214 return false;
7215 this->emitLabel(ContinueLabel);
7216 }
7217
7218 this->emitLabel(EndLabel);
7219
7220 return WholeLoopScope.destroyLocals();
7221}
7222
7223template <class Emitter>
7224bool Compiler<Emitter>::emitLambdaStaticInvokerBody(const CXXMethodDecl *MD) {
7225 assert(MD->isLambdaStaticInvoker());
7226 assert(MD->hasBody());
7227 assert(cast<CompoundStmt>(MD->getBody())->body_empty());
7228
7229 const CXXRecordDecl *ClosureClass = MD->getParent();
7230 const FunctionDecl *LambdaCallOp;
7231 assert(ClosureClass->captures().empty());
7232 if (ClosureClass->isGenericLambda()) {
7233 LambdaCallOp = ClosureClass->getLambdaCallOperator();
7234 assert(MD->isFunctionTemplateSpecialization() &&
7235 "A generic lambda's static-invoker function must be a "
7236 "template specialization");
7238 FunctionTemplateDecl *CallOpTemplate =
7239 LambdaCallOp->getDescribedFunctionTemplate();
7240 void *InsertPos = nullptr;
7241 const FunctionDecl *CorrespondingCallOpSpecialization =
7242 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7243 assert(CorrespondingCallOpSpecialization);
7244 LambdaCallOp = CorrespondingCallOpSpecialization;
7245 } else {
7246 LambdaCallOp = ClosureClass->getLambdaCallOperator();
7247 }
7248 assert(ClosureClass->captures().empty());
7249 const Function *Func = this->getFunction(LambdaCallOp);
7250 if (!Func)
7251 return false;
7252 assert(Func->hasThisPointer());
7253 assert(Func->getNumParams() == (MD->getNumParams() + 1 + Func->hasRVO()));
7254
7255 if (Func->hasRVO()) {
7256 if (!this->emitRVOPtr(MD))
7257 return false;
7258 }
7259
7260 // The lambda call operator needs an instance pointer, but we don't have
7261 // one here, and we don't need one either because the lambda cannot have
7262 // any captures, as verified above. Emit a null pointer. This is then
7263 // special-cased when interpreting to not emit any misleading diagnostics.
7264 if (!this->emitNullPtr(0, nullptr, MD))
7265 return false;
7266
7267 // Forward all arguments from the static invoker to the lambda call operator.
7268 for (const ParmVarDecl *PVD : MD->parameters()) {
7269 auto It = this->Params.find(PVD);
7270 assert(It != this->Params.end());
7271
7272 // We do the lvalue-to-rvalue conversion manually here, so no need
7273 // to care about references.
7274 PrimType ParamType = this->classify(PVD->getType()).value_or(PT_Ptr);
7275 if (!this->emitGetParam(ParamType, It->second.Index, MD))
7276 return false;
7277 }
7278
7279 if (!this->emitCall(Func, 0, LambdaCallOp))
7280 return false;
7281
7282 this->emitCleanup();
7283 if (ReturnType)
7284 return this->emitRet(*ReturnType, MD);
7285
7286 // Nothing to do, since we emitted the RVO pointer above.
7287 return this->emitRetVoid(MD);
7288}
7289
7290template <class Emitter>
7291bool Compiler<Emitter>::checkLiteralType(const Expr *E) {
7292 if (Ctx.getLangOpts().CPlusPlus23)
7293 return true;
7294
7295 if (!E->isPRValue() || E->getType()->isLiteralType(Ctx.getASTContext()))
7296 return true;
7297
7298 return this->emitCheckLiteralType(E->getType().getTypePtr(), E);
7299}
7300
7302 const Expr *InitExpr = Init->getInit();
7303
7304 if (!Init->isWritten() && !Init->isInClassMemberInitializer() &&
7305 !isa<CXXConstructExpr>(InitExpr))
7306 return true;
7307
7308 if (const auto *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
7309 const CXXConstructorDecl *Ctor = CE->getConstructor();
7310 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
7311 Ctor->isTrivial())
7312 return true;
7313 }
7314
7315 return false;
7316}
7317
7318template <class Emitter>
7319bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
7320 assert(!ReturnType);
7321
7322 // Only start the lifetime of the instance pointer.
7323 if (!this->emitStartThisLifetime1(Ctor))
7324 return false;
7325
7326 auto emitFieldInitializer = [&](const Record::Field *F, unsigned FieldOffset,
7327 const Expr *InitExpr,
7328 bool Activate = false) -> bool {
7329 // We don't know what to do with these, so just return false.
7330 if (InitExpr->getType().isNull())
7331 return false;
7332
7333 if (OptPrimType T = this->classify(InitExpr)) {
7334 if (Activate && !this->emitActivateThisField(FieldOffset, InitExpr))
7335 return false;
7336
7337 if (!this->visit(InitExpr))
7338 return false;
7339
7340 if (F->isBitField())
7341 return this->emitInitThisBitField(*T, FieldOffset, F->bitWidth(),
7342 InitExpr);
7343 return this->emitInitThisField(*T, FieldOffset, InitExpr);
7344 }
7345 // Non-primitive case. Get a pointer to the field-to-initialize
7346 // on the stack and call visitInitialzer() for it.
7347 InitLinkScope<Emitter> FieldScope(this, InitLink::Field(F->Offset));
7348 if (!this->emitGetPtrThisField(FieldOffset, InitExpr))
7349 return false;
7350
7351 if (Activate && !this->emitActivate(InitExpr))
7352 return false;
7353
7354 return this->visitInitializerPop(InitExpr);
7355 };
7356
7357 const RecordDecl *RD = Ctor->getParent();
7358 const Record *R = this->getRecord(RD);
7359 if (!R)
7360 return false;
7361 bool IsUnion = R->isUnion();
7362
7363 // Default union copy and move ctors are special.
7364 if (IsUnion && Ctor->isCopyOrMoveConstructor() && Ctor->isDefaulted()) {
7366
7367 // No special case for NumFields == 0 here, so the Memcpy op
7368 // below also does its checks in those cases.
7369
7370 assert(cast<CompoundStmt>(Ctor->getBody())->body_empty());
7371 if (!this->emitThis(Ctor))
7372 return false;
7373
7374 if (!this->emitGetParam(PT_Ptr, /*ParamIndex=*/0, Ctor))
7375 return false;
7376
7377 return this->emitMemcpy(Ctor) && this->emitPopPtr(Ctor) &&
7378 this->emitRetVoid(Ctor);
7379 }
7380
7381 unsigned FieldInits = 0;
7383 for (const auto *Init : Ctor->inits()) {
7384 // Scope needed for the initializers.
7385 LocalScope<Emitter> Scope(this, ScopeKind::FullExpression);
7386
7387 const Expr *InitExpr = Init->getInit();
7388 if (const FieldDecl *Member = Init->getMember()) {
7389 const Record::Field *F = R->getField(Member);
7390
7393 if (!emitFieldInitializer(F, F->Offset, InitExpr, IsUnion))
7394 return false;
7395 ++FieldInits;
7396 } else if (const Type *Base = Init->getBaseClass()) {
7397 const auto *BaseDecl = Base->getAsCXXRecordDecl();
7398 assert(BaseDecl);
7399
7400 if (Init->isBaseVirtual()) {
7401 assert(R->getVirtualBase(BaseDecl));
7402 if (!this->emitGetPtrThisVirtBase(BaseDecl, InitExpr))
7403 return false;
7404
7405 } else {
7406 // Base class initializer.
7407 // Get This Base and call initializer on it.
7408 const Record::Base *B = R->getBase(BaseDecl);
7409 assert(B);
7410 if (!this->emitGetPtrThisBase(B->Offset, InitExpr))
7411 return false;
7412 }
7413
7414 if (!this->visitInitializerPop(InitExpr))
7415 return false;
7416 } else if (const IndirectFieldDecl *IFD = Init->getIndirectMember()) {
7419 unsigned ChainSize = IFD->getChainingSize();
7420 assert(ChainSize >= 2);
7421
7422 unsigned NestedFieldOffset = 0;
7423 const Record::Field *NestedField = nullptr;
7424 for (unsigned I = 0; I != ChainSize; ++I) {
7425 const auto *FD = cast<FieldDecl>(IFD->chain()[I]);
7426 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
7427 assert(FieldRecord);
7428
7429 NestedField = FieldRecord->getField(FD);
7430 assert(NestedField);
7431 IsUnion = IsUnion || FieldRecord->isUnion();
7432
7433 NestedFieldOffset += NestedField->Offset;
7434
7435 // Add a new InitChainLink for the record, but not for the final field.
7436 if (I != ChainSize - 1)
7437 InitStack.push_back(InitLink::Field(NestedField->Offset));
7438 }
7439 assert(NestedField);
7440
7442 if (!emitFieldInitializer(NestedField, NestedFieldOffset, InitExpr,
7443 IsUnion))
7444 return false;
7445
7446 // Mark all chain links as initialized.
7447 unsigned InitFieldOffset = 0;
7448 for (const NamedDecl *ND : IFD->chain().drop_back()) {
7449 const auto *FD = cast<FieldDecl>(ND);
7450 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
7451 assert(FieldRecord);
7452 NestedField = FieldRecord->getField(FD);
7453 InitFieldOffset += NestedField->Offset;
7454 assert(NestedField);
7455 if (!this->emitGetPtrThisField(InitFieldOffset, InitExpr))
7456 return false;
7457 if (!this->emitFinishInitPop(InitExpr))
7458 return false;
7459 }
7460
7461 InitStack.pop_back_n(ChainSize - 1);
7462
7463 } else {
7464 assert(Init->isDelegatingInitializer());
7465 if (!this->emitThis(InitExpr))
7466 return false;
7467 if (!this->visitInitializerPop(Init->getInit()))
7468 return false;
7469 }
7470
7471 if (!Scope.destroyLocals())
7472 return false;
7473 }
7474
7475 if (FieldInits != R->getNumFields()) {
7476 assert(FieldInits < R->getNumFields());
7477 // Start the lifetime of all members.
7478 if (!this->emitStartThisLifetime(Ctor))
7479 return false;
7480 }
7481
7482 if (const Stmt *Body = Ctor->getBody()) {
7483 // Only emit the CtorCheck op for non-empty CompoundStmt bodies.
7484 // For non-CompoundStmts, always assume they are non-empty and emit it.
7485 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
7486 if (!CS->body_empty() && !this->emitCtorCheck(SourceInfo{}))
7487 return false;
7488 } else {
7489 if (!this->emitCtorCheck(SourceInfo{}))
7490 return false;
7491 }
7492
7493 if (!visitStmt(Body))
7494 return false;
7495 }
7496
7497 return this->emitRetVoid(SourceInfo{});
7498}
7499
7500template <class Emitter>
7501bool Compiler<Emitter>::compileDestructor(const CXXDestructorDecl *Dtor) {
7502 const RecordDecl *RD = Dtor->getParent();
7503 const Record *R = this->getRecord(RD);
7504 if (!R)
7505 return false;
7506
7507 if (!Dtor->isTrivial() && Dtor->getBody()) {
7508 if (!this->visitStmt(Dtor->getBody()))
7509 return false;
7510 }
7511
7512 if (!this->emitThis(Dtor))
7513 return false;
7514
7515 if (!this->emitCheckDestruction(Dtor))
7516 return false;
7517
7518 assert(R);
7519 if (!R->isUnion()) {
7520
7522 // First, destroy all fields.
7523 for (const Record::Field &Field : llvm::reverse(R->fields())) {
7524 const Descriptor *D = Field.Desc;
7525 if (D->hasTrivialDtor())
7526 continue;
7527 if (!this->emitGetPtrField(Field.Offset, SourceInfo{}))
7528 return false;
7529 if (!this->emitDestructionPop(D, SourceInfo{}))
7530 return false;
7531 }
7532 }
7533
7534 for (const Record::Base &Base : llvm::reverse(R->bases())) {
7535 if (Base.R->hasTrivialDtor())
7536 continue;
7537 if (!this->emitGetPtrBase(Base.Offset, SourceInfo{}))
7538 return false;
7539 if (!this->emitRecordDestructionPop(Base.R, {}))
7540 return false;
7541 }
7542
7543 if (!this->emitMarkDestroyed(Dtor))
7544 return false;
7545
7546 // FIXME: Virtual bases.
7547 return this->emitPopPtr(Dtor) && this->emitRetVoid(Dtor);
7548}
7549
7550template <class Emitter>
7551bool Compiler<Emitter>::compileUnionAssignmentOperator(
7552 const CXXMethodDecl *MD) {
7553 if (!this->emitThis(MD))
7554 return false;
7555
7556 if (!this->emitGetParam(PT_Ptr, /*ParamIndex=*/0, MD))
7557 return false;
7558
7559 return this->emitMemcpy(MD) && this->emitRet(PT_Ptr, MD);
7560}
7561
7562template <class Emitter>
7564 if (F->getReturnType()->isDependentType())
7565 return false;
7566
7567 // Classify the return type.
7568 ReturnType = this->classify(F->getReturnType());
7569
7570 this->CompilingFunction = F;
7571
7572 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(F))
7573 return this->compileConstructor(Ctor);
7574 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(F))
7575 return this->compileDestructor(Dtor);
7576
7577 // Emit custom code if this is a lambda static invoker.
7578 if (const auto *MD = dyn_cast<CXXMethodDecl>(F)) {
7579 const RecordDecl *RD = MD->getParent();
7580
7581 if (RD->isUnion() &&
7583 return this->compileUnionAssignmentOperator(MD);
7584
7585 if (MD->isLambdaStaticInvoker())
7586 return this->emitLambdaStaticInvokerBody(MD);
7587 }
7588
7589 // Regular functions.
7590 if (const auto *Body = F->getBody())
7591 if (!visitStmt(Body))
7592 return false;
7593
7594 // Emit a guard return to protect against a code path missing one.
7595 if (F->getReturnType()->isVoidType())
7596 return this->emitRetVoid(SourceInfo{});
7597 return this->emitNoRet(SourceInfo{});
7598}
7599
7600static uint32_t getBitWidth(const Expr *E) {
7601 assert(E->refersToBitField());
7602 const auto *ME = cast<MemberExpr>(E);
7603 const auto *FD = cast<FieldDecl>(ME->getMemberDecl());
7604 return FD->getBitWidthValue();
7605}
7606
7607template <class Emitter>
7609 if (E->containsErrors())
7610 return false;
7611
7612 const Expr *SubExpr = E->getSubExpr();
7613 if (SubExpr->getType()->isAnyComplexType())
7614 return this->VisitComplexUnaryOperator(E);
7615 if (SubExpr->getType()->isVectorType())
7616 return this->VisitVectorUnaryOperator(E);
7617 if (SubExpr->getType()->isFixedPointType())
7618 return this->VisitFixedPointUnaryOperator(E);
7619 OptPrimType T = classify(SubExpr->getType());
7620
7621 switch (E->getOpcode()) {
7622 case UO_PostInc: { // x++
7623 if (!Ctx.getLangOpts().CPlusPlus14)
7624 return this->emitInvalid(E);
7625 if (!T)
7626 return this->emitError(E);
7627
7628 if (!this->visit(SubExpr))
7629 return false;
7630
7631 if (T == PT_Ptr) {
7632 if (!this->emitIncPtr(E))
7633 return false;
7634
7635 return DiscardResult ? this->emitPopPtr(E) : true;
7636 }
7637
7638 if (T == PT_Float)
7639 return DiscardResult ? this->emitIncfPop(getFPOptions(E), E)
7640 : this->emitIncf(getFPOptions(E), E);
7641
7642 if (SubExpr->refersToBitField())
7643 return DiscardResult ? this->emitIncPopBitfield(*T, E->canOverflow(),
7644 getBitWidth(SubExpr), E)
7645 : this->emitIncBitfield(*T, E->canOverflow(),
7646 getBitWidth(SubExpr), E);
7647
7648 return DiscardResult ? this->emitIncPop(*T, E->canOverflow(), E)
7649 : this->emitInc(*T, E->canOverflow(), E);
7650 }
7651 case UO_PostDec: { // x--
7652 if (!Ctx.getLangOpts().CPlusPlus14)
7653 return this->emitInvalid(E);
7654 if (!T)
7655 return this->emitError(E);
7656
7657 if (!this->visit(SubExpr))
7658 return false;
7659
7660 if (T == PT_Ptr) {
7661 if (!this->emitDecPtr(E))
7662 return false;
7663
7664 return DiscardResult ? this->emitPopPtr(E) : true;
7665 }
7666
7667 if (T == PT_Float)
7668 return DiscardResult ? this->emitDecfPop(getFPOptions(E), E)
7669 : this->emitDecf(getFPOptions(E), E);
7670
7671 if (SubExpr->refersToBitField()) {
7672 return DiscardResult ? this->emitDecPopBitfield(*T, E->canOverflow(),
7673 getBitWidth(SubExpr), E)
7674 : this->emitDecBitfield(*T, E->canOverflow(),
7675 getBitWidth(SubExpr), E);
7676 }
7677
7678 return DiscardResult ? this->emitDecPop(*T, E->canOverflow(), E)
7679 : this->emitDec(*T, E->canOverflow(), E);
7680 }
7681 case UO_PreInc: { // ++x
7682 if (!Ctx.getLangOpts().CPlusPlus14)
7683 return this->emitInvalid(E);
7684 if (!T)
7685 return this->emitError(E);
7686
7687 if (!this->visit(SubExpr))
7688 return false;
7689
7690 if (T == PT_Ptr) {
7691 if (!this->emitLoadPtr(E))
7692 return false;
7693 if (!this->emitConstUint8(1, E))
7694 return false;
7695 if (!this->emitAddOffsetUint8(E))
7696 return false;
7697 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
7698 }
7699
7700 // Post-inc and pre-inc are the same if the value is to be discarded.
7701 if (DiscardResult) {
7702 if (T == PT_Float)
7703 return this->emitIncfPop(getFPOptions(E), E);
7704 if (SubExpr->refersToBitField())
7705 return DiscardResult ? this->emitIncPopBitfield(*T, E->canOverflow(),
7706 getBitWidth(SubExpr), E)
7707 : this->emitIncBitfield(*T, E->canOverflow(),
7708 getBitWidth(SubExpr), E);
7709 return this->emitIncPop(*T, E->canOverflow(), E);
7710 }
7711
7712 if (T == PT_Float) {
7713 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
7714 if (!this->emitLoadFloat(E))
7715 return false;
7716 APFloat F(TargetSemantics, 1);
7717 if (!this->emitFloat(F, E))
7718 return false;
7719
7720 if (!this->emitAddf(getFPOptions(E), E))
7721 return false;
7722 if (!this->emitStoreFloat(E))
7723 return false;
7724 } else if (SubExpr->refersToBitField()) {
7725 assert(isIntegerOrBoolType(*T));
7726 if (!this->emitPreIncBitfield(*T, E->canOverflow(), getBitWidth(SubExpr),
7727 E))
7728 return false;
7729 } else {
7730 assert(isIntegerOrBoolType(*T));
7731 if (!this->emitPreInc(*T, E->canOverflow(), E))
7732 return false;
7733 }
7734 return E->isGLValue() || this->emitLoadPop(*T, E);
7735 }
7736 case UO_PreDec: { // --x
7737 if (!Ctx.getLangOpts().CPlusPlus14)
7738 return this->emitInvalid(E);
7739 if (!T)
7740 return this->emitError(E);
7741
7742 if (!this->visit(SubExpr))
7743 return false;
7744
7745 if (T == PT_Ptr) {
7746 if (!this->emitLoadPtr(E))
7747 return false;
7748 if (!this->emitConstUint8(1, E))
7749 return false;
7750 if (!this->emitSubOffsetUint8(E))
7751 return false;
7752 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
7753 }
7754
7755 // Post-dec and pre-dec are the same if the value is to be discarded.
7756 if (DiscardResult) {
7757 if (T == PT_Float)
7758 return this->emitDecfPop(getFPOptions(E), E);
7759 if (SubExpr->refersToBitField())
7760 return DiscardResult ? this->emitDecPopBitfield(*T, E->canOverflow(),
7761 getBitWidth(SubExpr), E)
7762 : this->emitDecBitfield(*T, E->canOverflow(),
7763 getBitWidth(SubExpr), E);
7764 return this->emitDecPop(*T, E->canOverflow(), E);
7765 }
7766
7767 if (T == PT_Float) {
7768 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
7769 if (!this->emitLoadFloat(E))
7770 return false;
7771 APFloat F(TargetSemantics, 1);
7772 if (!this->emitFloat(F, E))
7773 return false;
7774
7775 if (!this->emitSubf(getFPOptions(E), E))
7776 return false;
7777 if (!this->emitStoreFloat(E))
7778 return false;
7779 } else if (SubExpr->refersToBitField()) {
7780 assert(isIntegerOrBoolType(*T));
7781 if (!this->emitPreDecBitfield(*T, E->canOverflow(), getBitWidth(SubExpr),
7782 E))
7783 return false;
7784 } else {
7785 assert(isIntegerOrBoolType(*T));
7786 if (!this->emitPreDec(*T, E->canOverflow(), E))
7787 return false;
7788 }
7789 return E->isGLValue() || this->emitLoadPop(*T, E);
7790 }
7791 case UO_LNot: // !x
7792 if (!T)
7793 return this->emitError(E);
7794
7795 if (DiscardResult)
7796 return this->discard(SubExpr);
7797
7798 if (!this->visitBool(SubExpr))
7799 return false;
7800
7801 if (!this->emitInv(E))
7802 return false;
7803
7804 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
7805 return this->emitCast(PT_Bool, ET, E);
7806 return true;
7807 case UO_Minus: // -x
7808 if (!T)
7809 return this->emitError(E);
7810
7811 if (!this->visit(SubExpr))
7812 return false;
7813 return DiscardResult ? this->emitPop(*T, E) : this->emitNeg(*T, E);
7814 case UO_Plus: // +x
7815 if (!T)
7816 return this->emitError(E);
7817
7818 if (!this->visit(SubExpr)) // noop
7819 return false;
7820 return DiscardResult ? this->emitPop(*T, E) : true;
7821 case UO_AddrOf: // &x
7822 if (E->getType()->isMemberPointerType()) {
7823 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7824 // member can be formed.
7825 if (DiscardResult)
7826 return true;
7827 return this->emitGetMemberPtr(cast<DeclRefExpr>(SubExpr)->getDecl(), E);
7828 }
7829 // [C11 6.5.3.2p3]: if the operand of '&' is the result of a unary '*'
7830 // operator, neither operator is evaluated and the result is as if both
7831 // were omitted. So '&*q' is just 'q' with no dereference; delegate to the
7832 // pointer operand directly instead of to the '*' (which would emit a null
7833 // check), so that e.g. '&*(int *)0' is not rejected.
7834 if (!Ctx.getLangOpts().CPlusPlus) {
7835 const Expr *Sub = SubExpr->IgnoreParens();
7836 if (const auto *Deref = dyn_cast<UnaryOperator>(Sub);
7837 Deref && Deref->getOpcode() == UO_Deref)
7838 return this->delegate(Deref->getSubExpr());
7839 }
7840 // We should already have a pointer when we get here.
7841 return this->delegate(SubExpr);
7842 case UO_Deref: // *x
7843 if (DiscardResult)
7844 return this->discard(SubExpr);
7845
7846 if (!this->visit(SubExpr))
7847 return false;
7848
7849 if (!SubExpr->getType()->isFunctionPointerType() && !this->emitCheckNull(E))
7850 return false;
7851
7852 if (classifyPrim(SubExpr) == PT_Ptr)
7853 return this->emitNarrowPtr(E);
7854 return true;
7855
7856 case UO_Not: // ~x
7857 if (!T)
7858 return this->emitError(E);
7859
7860 if (!this->visit(SubExpr))
7861 return false;
7862 return DiscardResult ? this->emitPop(*T, E) : this->emitComp(*T, E);
7863 case UO_Real: // __real x
7864 if (!T)
7865 return false;
7866 return this->delegate(SubExpr);
7867 case UO_Imag: { // __imag x
7868 if (!T)
7869 return false;
7870 if (!this->discard(SubExpr))
7871 return false;
7872 return DiscardResult
7873 ? true
7874 : this->visitZeroInitializer(*T, SubExpr->getType(), SubExpr);
7875 }
7876 case UO_Extension:
7877 return this->delegate(SubExpr);
7878 case UO_Coawait:
7879 assert(false && "Unhandled opcode");
7880 }
7881
7882 return false;
7883}
7884
7885template <class Emitter>
7887 const Expr *SubExpr = E->getSubExpr();
7888 assert(SubExpr->getType()->isAnyComplexType());
7889
7890 if (DiscardResult)
7891 return this->discard(SubExpr);
7892
7893 OptPrimType ResT = classify(E);
7894 auto prepareResult = [=]() -> bool {
7895 if (!ResT && !Initializing) {
7896 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
7897 if (!LocalIndex)
7898 return false;
7899 return this->emitGetPtrLocal(*LocalIndex, E);
7900 }
7901
7902 return true;
7903 };
7904
7905 // The offset of the temporary, if we created one.
7906 unsigned SubExprOffset = ~0u;
7907 auto createTemp = [=, &SubExprOffset]() -> bool {
7908 SubExprOffset =
7909 this->allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
7910 if (!this->visit(SubExpr))
7911 return false;
7912 return this->emitSetLocal(PT_Ptr, SubExprOffset, E);
7913 };
7914
7915 PrimType ElemT = classifyComplexElementType(SubExpr->getType());
7916 auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
7917 if (!this->emitGetLocal(PT_Ptr, Offset, E))
7918 return false;
7919 return this->emitArrayElemPop(ElemT, Index, E);
7920 };
7921
7922 switch (E->getOpcode()) {
7923 case UO_Minus: // -x
7924 if (!prepareResult())
7925 return false;
7926 if (!createTemp())
7927 return false;
7928 for (unsigned I = 0; I != 2; ++I) {
7929 if (!getElem(SubExprOffset, I))
7930 return false;
7931 if (!this->emitNeg(ElemT, E))
7932 return false;
7933 if (!this->emitInitElem(ElemT, I, E))
7934 return false;
7935 }
7936 break;
7937
7938 case UO_Plus: // +x
7939 case UO_AddrOf: // &x
7940 case UO_Deref: // *x
7941 return this->delegate(SubExpr);
7942
7943 case UO_LNot:
7944 if (!this->visit(SubExpr))
7945 return false;
7946 if (!this->emitComplexBoolCast(SubExpr))
7947 return false;
7948 if (!this->emitInv(E))
7949 return false;
7950 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
7951 return this->emitCast(PT_Bool, ET, E);
7952 return true;
7953
7954 case UO_Real:
7955 return this->emitComplexReal(SubExpr);
7956
7957 case UO_Imag:
7958 if (!this->visit(SubExpr))
7959 return false;
7960
7961 if (SubExpr->isLValue()) {
7962 if (!this->emitConstUint8(1, E))
7963 return false;
7964 return this->emitArrayElemPtrPopUint8(E);
7965 }
7966
7967 // Since our _Complex implementation does not map to a primitive type,
7968 // we sometimes have to do the lvalue-to-rvalue conversion here manually.
7969 return this->emitArrayElemPop(classifyPrim(E->getType()), 1, E);
7970
7971 case UO_Not: // ~x
7972 if (!this->delegate(SubExpr))
7973 return false;
7974 // Negate the imaginary component.
7975 if (!this->emitArrayElem(ElemT, 1, E))
7976 return false;
7977 if (!this->emitNeg(ElemT, E))
7978 return false;
7979 if (!this->emitInitElem(ElemT, 1, E))
7980 return false;
7981 return DiscardResult ? this->emitPopPtr(E) : true;
7982
7983 case UO_Extension:
7984 return this->delegate(SubExpr);
7985
7986 default:
7987 return this->emitInvalid(E);
7988 }
7989
7990 return true;
7991}
7992
7993template <class Emitter>
7995 const Expr *SubExpr = E->getSubExpr();
7996 assert(SubExpr->getType()->isVectorType());
7997
7998 if (DiscardResult)
7999 return this->discard(SubExpr);
8000
8001 auto UnaryOp = E->getOpcode();
8002 if (UnaryOp == UO_Extension)
8003 return this->delegate(SubExpr);
8004
8005 if (UnaryOp != UO_Plus && UnaryOp != UO_Minus && UnaryOp != UO_LNot &&
8006 UnaryOp != UO_Not && UnaryOp != UO_AddrOf)
8007 return this->emitInvalid(E);
8008
8009 // Nothing to do here.
8010 if (UnaryOp == UO_Plus || UnaryOp == UO_AddrOf)
8011 return this->delegate(SubExpr);
8012
8013 if (!Initializing) {
8014 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
8015 if (!LocalIndex)
8016 return false;
8017 if (!this->emitGetPtrLocal(*LocalIndex, E))
8018 return false;
8019 }
8020
8021 // The offset of the temporary, if we created one.
8022 unsigned SubExprOffset =
8023 this->allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
8024 if (!this->visit(SubExpr))
8025 return false;
8026 if (!this->emitSetLocal(PT_Ptr, SubExprOffset, E))
8027 return false;
8028
8029 const auto *VecTy = SubExpr->getType()->getAs<VectorType>();
8030 PrimType ElemT = classifyVectorElementType(SubExpr->getType());
8031 auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
8032 if (!this->emitGetLocal(PT_Ptr, Offset, E))
8033 return false;
8034 return this->emitArrayElemPop(ElemT, Index, E);
8035 };
8036
8037 switch (UnaryOp) {
8038 case UO_Minus:
8039 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8040 if (!getElem(SubExprOffset, I))
8041 return false;
8042 if (!this->emitNeg(ElemT, E))
8043 return false;
8044 if (!this->emitInitElem(ElemT, I, E))
8045 return false;
8046 }
8047 break;
8048 case UO_LNot: { // !x
8049 // In C++, the logic operators !, &&, || are available for vectors. !v is
8050 // equivalent to v == 0.
8051 //
8052 // The result of the comparison is a vector of the same width and number of
8053 // elements as the comparison operands with a signed integral element type.
8054 //
8055 // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html
8056 QualType ResultVecTy = E->getType();
8057 PrimType ResultVecElemT =
8058 classifyPrim(ResultVecTy->getAs<VectorType>()->getElementType());
8059 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8060 if (!getElem(SubExprOffset, I))
8061 return false;
8062 // operator ! on vectors returns -1 for 'truth', so negate it.
8063 if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
8064 return false;
8065 if (!this->emitInv(E))
8066 return false;
8067 if (!this->emitPrimCast(PT_Bool, ElemT, VecTy->getElementType(), E))
8068 return false;
8069 if (!this->emitNeg(ElemT, E))
8070 return false;
8071 if (ElemT != ResultVecElemT &&
8072 !this->emitPrimCast(ElemT, ResultVecElemT, ResultVecTy, E))
8073 return false;
8074 if (!this->emitInitElem(ResultVecElemT, I, E))
8075 return false;
8076 }
8077 break;
8078 }
8079 case UO_Not: // ~x
8080 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8081 if (!getElem(SubExprOffset, I))
8082 return false;
8083 if (ElemT == PT_Bool) {
8084 if (!this->emitInv(E))
8085 return false;
8086 } else {
8087 if (!this->emitComp(ElemT, E))
8088 return false;
8089 }
8090 if (!this->emitInitElem(ElemT, I, E))
8091 return false;
8092 }
8093 break;
8094 default:
8095 llvm_unreachable("Unsupported unary operators should be handled up front");
8096 }
8097 return true;
8098}
8099
8100template <class Emitter>
8102 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
8103 if (DiscardResult)
8104 return true;
8105 return this->emitConst(ECD->getInitVal(), E);
8106 }
8107 if (const auto *FuncDecl = dyn_cast<FunctionDecl>(D)) {
8108 if (DiscardResult)
8109 return true;
8110 const Function *F = getFunction(FuncDecl);
8111 return F && this->emitGetFnPtr(F, E);
8112 }
8113 if (const auto *TPOD = dyn_cast<TemplateParamObjectDecl>(D)) {
8114 TPOD = TPOD->getFirstDecl();
8115 if (DiscardResult)
8116 return true;
8117 if (UnsignedOrNone GlobalIndex = P.getGlobal(TPOD))
8118 return this->emitGetPtrGlobal(*GlobalIndex, E);
8119
8120 if (UnsignedOrNone Index = P.getOrCreateGlobal(TPOD)) {
8121 if (OptPrimType T = classify(TPOD->getType())) {
8122 if (!this->visitAPValue(TPOD->getValue(), *T, E))
8123 return false;
8124 return this->emitInitGlobal(*T, *Index, E);
8125 }
8126
8127 if (!this->emitGetPtrGlobal(*Index, E))
8128 return false;
8129 if (!this->visitAPValueInitializer(TPOD->getValue(), E, TPOD->getType()))
8130 return false;
8131 return this->emitFinishInit(E);
8132 }
8133 return false;
8134 }
8135
8136 // References are implemented via pointers, so when we see a DeclRefExpr
8137 // pointing to a reference, we need to get its value directly (i.e. the
8138 // pointer to the actual value) instead of a pointer to the pointer to the
8139 // value.
8140 QualType DeclType = D->getType();
8141 bool IsReference = DeclType->isReferenceType();
8142
8143 auto maybePopPtr = [&]() -> bool {
8144 if (DiscardResult)
8145 return this->emitPopPtr(E);
8146 return true;
8147 };
8148
8149 // Function parameters.
8150 // Note that it's important to check them first since we might have a local
8151 // variable created for a ParmVarDecl as well.
8152 if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
8153 if (DiscardResult)
8154 return true;
8155
8156 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
8157 !DeclType->isIntegralOrEnumerationType()) {
8158 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8159 /*InitializerFailed=*/false, E);
8160 }
8161 if (auto It = this->Params.find(PVD); It != this->Params.end()) {
8162 if (IsReference || !It->second.IsPtr)
8163 return this->emitGetParam(classifyPrim(E), It->second.Index, E);
8164
8165 return this->emitGetPtrParam(It->second.Index, E);
8166 }
8167
8168 if (!Ctx.getLangOpts().CPlusPlus23 && IsReference && !Locals.contains(D))
8169 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8170 /*InitializerFailed=*/false, E);
8171 }
8172
8173 // Local variables.
8174 if (auto It = Locals.find(D); It != Locals.end()) {
8175 const unsigned Offset = It->second.Offset;
8176 if (IsReference) {
8177 assert(classifyPrim(E) == PT_Ptr);
8178 return this->emitGetRefLocal(Offset, E) && maybePopPtr();
8179 }
8180 return this->emitGetPtrLocal(Offset, E) && maybePopPtr();
8181 }
8182 // Global variables.
8183 if (auto GlobalIndex = P.getGlobal(D)) {
8184 if (IsReference) {
8185 if (!Ctx.getLangOpts().CPlusPlus11)
8186 return this->emitGetGlobal(classifyPrim(E), *GlobalIndex, E);
8187 if (!Ctx.getLangOpts().CPlusPlus23)
8188 return this->emitGetGlobalUnchecked(classifyPrim(E), *GlobalIndex, E);
8189
8190 return this->emitGetRefGlobal(*GlobalIndex, E) && maybePopPtr();
8191 }
8192
8193 return this->emitGetPtrGlobal(*GlobalIndex, E) && maybePopPtr();
8194 }
8195
8196 // In case we need to re-visit a declaration.
8197 auto revisit = [&](const VarDecl *VD,
8198 bool IsConstexprUnknown = true) -> bool {
8200 IsConstexprUnknown);
8201 if (!this->emitPushCC(VD->hasConstantInitialization(), E))
8202 return false;
8203 auto VarState = this->visitDecl(VD);
8204
8205 if (!this->emitPopCC(E))
8206 return false;
8207
8208 if (VarState.notCreated())
8209 return true;
8210 if (!VarState)
8211 return false;
8212 // Retry.
8213 return this->visitDeclRef(D, E);
8214 };
8215
8216 if constexpr (!std::is_same_v<Emitter, EvalEmitter>) {
8217 // Lambda captures.
8218 if (auto It = this->LambdaCaptures.find(D);
8219 It != this->LambdaCaptures.end()) {
8220 auto [Offset, IsPtr] = It->second;
8221
8222 if (IsPtr)
8223 return this->emitGetThisFieldPtr(Offset, E) && maybePopPtr();
8224 return this->emitGetPtrThisField(Offset, E) && maybePopPtr();
8225 }
8226 }
8227
8228 if (const auto *DRE = dyn_cast<DeclRefExpr>(E);
8229 DRE && DRE->refersToEnclosingVariableOrCapture()) {
8230 if (const auto *VD = dyn_cast<VarDecl>(D); VD && VD->isInitCapture())
8231 return revisit(VD);
8232 }
8233
8234 if (const auto *BD = dyn_cast<BindingDecl>(D))
8235 return this->delegate(BD->getBinding());
8236
8237 // Avoid infinite recursion.
8238 if (D == InitializingDecl) {
8239 if (DiscardResult)
8240 return true;
8241 return this->emitDummyPtr(D, E);
8242 }
8243
8244 // Try to lazily visit (or emit dummy pointers for) declarations
8245 // we haven't seen yet.
8246 const auto *VD = dyn_cast<VarDecl>(D);
8247 if (!VD)
8248 return this->emitError(E);
8249
8250 // For C.
8251 if (!Ctx.getLangOpts().CPlusPlus) {
8252 if (VD->getInit() && !VD->getInit()->isValueDependent() &&
8253 DeclType.isConstant(Ctx.getASTContext()) && !VD->isWeak() &&
8254 VD->evaluateValue())
8255 return revisit(VD, /*IsConstexprUnknown=*/false);
8256
8257 if (DiscardResult)
8258 return true;
8259 return this->emitDummyPtr(D, E);
8260 }
8261
8262 // ... and C++.
8263 const auto typeShouldBeVisited = [&](QualType T) -> bool {
8264 if (T.isConstant(Ctx.getASTContext()))
8265 return true;
8266 return T->isReferenceType();
8267 };
8268
8269 if ((VD->hasGlobalStorage() || VD->isStaticDataMember()) &&
8270 typeShouldBeVisited(DeclType)) {
8271 if (const Expr *Init = VD->getAnyInitializer();
8272 Init && !Init->isValueDependent()) {
8273 // Whether or not the evaluation is successul doesn't really matter
8274 // here -- we will create a global variable in any case, and that
8275 // will have the state of initializer evaluation attached.
8277 (void)Init->EvaluateAsInitializer(Ctx.getASTContext(), VD, Result, true);
8278 return this->visitDeclRef(D, E);
8279 }
8280 return revisit(VD, !VD->isConstexpr() && DeclType->isReferenceType());
8281 }
8282
8283 // FIXME: The evaluateValue() check here is a little ridiculous, since
8284 // it will ultimately call into Context::evaluateAsInitializer(). In
8285 // other words, we're evaluating the initializer, just to know if we can
8286 // evaluate the initializer.
8287 if (VD->isLocalVarDecl() && typeShouldBeVisited(DeclType) && VD->getInit() &&
8288 !VD->getInit()->isValueDependent()) {
8289 if (VD->evaluateValue()) {
8290 bool IsConstexprUnknown = !DeclType.isConstant(Ctx.getASTContext()) &&
8291 !DeclType->isReferenceType();
8292 // Revisit the variable declaration, but make sure it's associated with a
8293 // different evaluation, so e.g. mutable reads don't work on it.
8294 EvalIDScope _(Ctx);
8295 return revisit(VD, IsConstexprUnknown);
8296 } else if (Ctx.getLangOpts().CPlusPlus23 && IsReference)
8297 return revisit(VD, /*IsConstexprUnknown=*/true);
8298
8299 if (IsReference)
8300 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8301 /*InitializerFailed=*/true, E);
8302 }
8303
8304 if (DiscardResult)
8305 return true;
8306 return this->emitDummyPtr(
8307 D, E, Ctx.getLangOpts().CPlusPlus23 && DeclType->isReferenceType());
8308}
8309
8310template <class Emitter>
8312 const auto *D = E->getDecl();
8313 return this->visitDeclRef(D, E);
8314}
8315
8316template <class Emitter>
8318 const DesignatedInitUpdateExpr *E) {
8319 if (!this->visitInitializer(E->getBase()))
8320 return false;
8321 return this->visitInitializer(E->getUpdater());
8322}
8323
8324template <class Emitter> bool Compiler<Emitter>::emitCleanup() {
8325 for (VariableScope<Emitter> *C = VarScope; C; C = C->getParent()) {
8326 if (!C->destroyLocals())
8327 return false;
8328 }
8329 return true;
8330}
8331
8332template <class Emitter>
8333unsigned Compiler<Emitter>::collectBaseOffset(const QualType BaseType,
8334 const QualType DerivedType) {
8335 const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
8336 if (const auto *R = Ty->getPointeeCXXRecordDecl())
8337 return R;
8338 return Ty->getAsCXXRecordDecl();
8339 };
8340 const CXXRecordDecl *BaseDecl = extractRecordDecl(BaseType);
8341 const CXXRecordDecl *DerivedDecl = extractRecordDecl(DerivedType);
8342
8343 return Ctx.collectBaseOffset(BaseDecl, DerivedDecl);
8344}
8345
8346/// Emit casts from a PrimType to another PrimType.
8347template <class Emitter>
8348bool Compiler<Emitter>::emitPrimCast(PrimType FromT, PrimType ToT,
8349 QualType ToQT, const Expr *E) {
8350
8351 if (FromT == PT_Float) {
8352 // Floating to floating.
8353 if (ToT == PT_Float) {
8354 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
8355 return this->emitCastFP(ToSem, getRoundingMode(E), E);
8356 }
8357
8358 if (ToT == PT_IntAP)
8359 return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(ToQT),
8360 getFPOptions(E), E);
8361 if (ToT == PT_IntAPS)
8362 return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(ToQT),
8363 getFPOptions(E), E);
8364
8365 // Float to integral.
8366 if (isIntegerOrBoolType(ToT) || ToT == PT_Bool)
8367 return this->emitCastFloatingIntegral(ToT, getFPOptions(E), E);
8368 }
8369
8370 if (isIntegerOrBoolType(FromT) || FromT == PT_Bool) {
8371 if (ToT == PT_IntAP)
8372 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
8373 if (ToT == PT_IntAPS)
8374 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
8375
8376 // Integral to integral.
8377 if (isIntegerOrBoolType(ToT) || ToT == PT_Bool)
8378 return FromT != ToT ? this->emitCast(FromT, ToT, E) : true;
8379
8380 if (ToT == PT_Float) {
8381 // Integral to floating.
8382 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
8383 return this->emitCastIntegralFloating(FromT, ToSem, getFPOptions(E), E);
8384 }
8385 }
8386
8387 return false;
8388}
8389
8390template <class Emitter>
8391bool Compiler<Emitter>::emitIntegralCast(PrimType FromT, PrimType ToT,
8392 QualType ToQT, const Expr *E) {
8393 assert(FromT != ToT);
8394
8395 if (ToT == PT_IntAP)
8396 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
8397 if (ToT == PT_IntAPS)
8398 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
8399
8400 return this->emitCast(FromT, ToT, E);
8401}
8402
8403/// Emits __real(SubExpr)
8404template <class Emitter>
8405bool Compiler<Emitter>::emitComplexReal(const Expr *SubExpr) {
8406 assert(SubExpr->getType()->isAnyComplexType());
8407
8408 if (DiscardResult)
8409 return this->discard(SubExpr);
8410
8411 if (!this->visit(SubExpr))
8412 return false;
8413 if (SubExpr->isLValue()) {
8414 if (!this->emitConstUint8(0, SubExpr))
8415 return false;
8416 return this->emitArrayElemPtrPopUint8(SubExpr);
8417 }
8418
8419 // Rvalue, load the actual element.
8420 return this->emitArrayElemPop(classifyComplexElementType(SubExpr->getType()),
8421 0, SubExpr);
8422}
8423
8424template <class Emitter>
8425bool Compiler<Emitter>::emitComplexBoolCast(const Expr *E) {
8426 assert(!DiscardResult);
8427 PrimType ElemT = classifyComplexElementType(E->getType());
8428 // We emit the expression (__real(E) != 0 || __imag(E) != 0)
8429 // for us, that means (bool)E[0] || (bool)E[1]
8430 if (!this->emitArrayElem(ElemT, 0, E))
8431 return false;
8432 if (ElemT == PT_Float) {
8433 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
8434 return false;
8435 } else {
8436 if (!this->emitCast(ElemT, PT_Bool, E))
8437 return false;
8438 }
8439
8440 // We now have the bool value of E[0] on the stack.
8441 LabelTy LabelTrue = this->getLabel();
8442 if (!this->jumpTrue(LabelTrue, E))
8443 return false;
8444
8445 if (!this->emitArrayElemPop(ElemT, 1, E))
8446 return false;
8447 if (ElemT == PT_Float) {
8448 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
8449 return false;
8450 } else {
8451 if (!this->emitCast(ElemT, PT_Bool, E))
8452 return false;
8453 }
8454 // Leave the boolean value of E[1] on the stack.
8455 LabelTy EndLabel = this->getLabel();
8456 this->jump(EndLabel, E);
8457
8458 this->emitLabel(LabelTrue);
8459 if (!this->emitPopPtr(E))
8460 return false;
8461 if (!this->emitConstBool(true, E))
8462 return false;
8463
8464 this->fallthrough(EndLabel);
8465 this->emitLabel(EndLabel);
8466
8467 return true;
8468}
8469
8470template <class Emitter>
8471bool Compiler<Emitter>::emitComplexComparison(const Expr *LHS, const Expr *RHS,
8472 const BinaryOperator *E) {
8473 assert(E->isComparisonOp());
8474 assert(!Initializing);
8475 if (DiscardResult)
8476 return this->discard(LHS) && this->discard(RHS);
8477
8478 PrimType ElemT;
8479 bool LHSIsComplex;
8480 unsigned LHSOffset;
8481 if (LHS->getType()->isAnyComplexType()) {
8482 LHSIsComplex = true;
8483 ElemT = classifyComplexElementType(LHS->getType());
8484 LHSOffset = allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true);
8485 if (!this->visit(LHS))
8486 return false;
8487 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
8488 return false;
8489 } else {
8490 LHSIsComplex = false;
8491 PrimType LHST = classifyPrim(LHS->getType());
8492 LHSOffset = this->allocateLocalPrimitive(LHS, LHST, /*IsConst=*/true);
8493 if (!this->visit(LHS))
8494 return false;
8495 if (!this->emitSetLocal(LHST, LHSOffset, E))
8496 return false;
8497 }
8498
8499 bool RHSIsComplex;
8500 unsigned RHSOffset;
8501 if (RHS->getType()->isAnyComplexType()) {
8502 RHSIsComplex = true;
8503 ElemT = classifyComplexElementType(RHS->getType());
8504 RHSOffset = allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true);
8505 if (!this->visit(RHS))
8506 return false;
8507 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
8508 return false;
8509 } else {
8510 RHSIsComplex = false;
8511 PrimType RHST = classifyPrim(RHS->getType());
8512 RHSOffset = this->allocateLocalPrimitive(RHS, RHST, /*IsConst=*/true);
8513 if (!this->visit(RHS))
8514 return false;
8515 if (!this->emitSetLocal(RHST, RHSOffset, E))
8516 return false;
8517 }
8518
8519 auto getElem = [&](unsigned LocalOffset, unsigned Index,
8520 bool IsComplex) -> bool {
8521 if (IsComplex) {
8522 if (!this->emitGetLocal(PT_Ptr, LocalOffset, E))
8523 return false;
8524 return this->emitArrayElemPop(ElemT, Index, E);
8525 }
8526 return this->emitGetLocal(ElemT, LocalOffset, E);
8527 };
8528
8529 for (unsigned I = 0; I != 2; ++I) {
8530 // Get both values.
8531 if (!getElem(LHSOffset, I, LHSIsComplex))
8532 return false;
8533 if (!getElem(RHSOffset, I, RHSIsComplex))
8534 return false;
8535 // And compare them.
8536 if (!this->emitEQ(ElemT, E))
8537 return false;
8538
8539 if (!this->emitCastBoolUint8(E))
8540 return false;
8541 }
8542
8543 // We now have two bool values on the stack. Compare those.
8544 if (!this->emitAddUint8(E))
8545 return false;
8546 if (!this->emitConstUint8(2, E))
8547 return false;
8548
8549 if (E->getOpcode() == BO_EQ) {
8550 if (!this->emitEQUint8(E))
8551 return false;
8552 } else if (E->getOpcode() == BO_NE) {
8553 if (!this->emitNEUint8(E))
8554 return false;
8555 } else
8556 return false;
8557
8558 // In C, this returns an int.
8559 if (PrimType ResT = classifyPrim(E->getType()); ResT != PT_Bool)
8560 return this->emitCast(PT_Bool, ResT, E);
8561 return true;
8562}
8563
8564/// When calling this, we have a pointer of the local-to-destroy
8565/// on the stack.
8566/// Emit destruction of record types (or arrays of record types).
8567template <class Emitter>
8568bool Compiler<Emitter>::emitRecordDestructionPop(const Record *R,
8569 SourceInfo Loc) {
8570 assert(R);
8571 assert(!R->hasTrivialDtor());
8572 const CXXDestructorDecl *Dtor = R->getDestructor();
8573 assert(Dtor);
8574 const Function *DtorFunc = getFunction(Dtor);
8575 if (!DtorFunc)
8576 return false;
8577 assert(DtorFunc->hasThisPointer());
8578 assert(DtorFunc->getNumParams() == 1);
8579 return this->emitCall(DtorFunc, 0, Loc);
8580}
8581/// When calling this, we have a pointer of the local-to-destroy
8582/// on the stack.
8583/// Emit destruction of record types (or arrays of record types).
8584template <class Emitter>
8585bool Compiler<Emitter>::emitDestructionPop(const Descriptor *Desc,
8586 SourceInfo Loc) {
8587 assert(Desc);
8588 assert(!Desc->hasTrivialDtor());
8589
8590 // Arrays.
8591 if (Desc->isArray()) {
8592 const Descriptor *ElemDesc = Desc->ElemDesc;
8593 assert(ElemDesc);
8594
8595 unsigned N = Desc->getNumElems();
8596 if (N == 0)
8597 return this->emitPopPtr(Loc);
8598
8599 for (ssize_t I = N - 1; I >= 1; --I) {
8600 if (!this->emitConstUint64(I, Loc))
8601 return false;
8602 if (!this->emitArrayElemPtrUint64(Loc))
8603 return false;
8604 if (!this->emitDestructionPop(ElemDesc, Loc))
8605 return false;
8606 }
8607 // Last iteration, removes the instance pointer from the stack.
8608 if (!this->emitConstUint64(0, Loc))
8609 return false;
8610 if (!this->emitArrayElemPtrPopUint64(Loc))
8611 return false;
8612 return this->emitDestructionPop(ElemDesc, Loc);
8613 }
8614
8615 assert(Desc->ElemRecord);
8616 assert(!Desc->ElemRecord->hasTrivialDtor());
8617 return this->emitRecordDestructionPop(Desc->ElemRecord, Loc);
8618}
8619
8620/// Create a dummy pointer for the given decl (or expr) and
8621/// push a pointer to it on the stack.
8622template <class Emitter>
8623bool Compiler<Emitter>::emitDummyPtr(const DeclTy &D, const Expr *E, bool CU) {
8624 assert(!DiscardResult && "Should've been checked before");
8625 unsigned DummyID = P.getOrCreateDummy(D, CU);
8626
8627 if (!this->emitGetPtrGlobal(DummyID, E))
8628 return false;
8629 if (E->getType()->isVoidType())
8630 return true;
8631
8632 // Convert the dummy pointer to another pointer type if we have to.
8633 if (PrimType PT = classifyPrim(E); PT != PT_Ptr) {
8634 if (isPtrType(PT))
8635 return this->emitDecayPtr(PT_Ptr, PT, E);
8636 return false;
8637 }
8638 return true;
8639}
8640
8641template <class Emitter>
8642bool Compiler<Emitter>::emitFloat(const APFloat &F, SourceInfo Info) {
8643 if (Floating::singleWord(F.getSemantics()))
8644 return this->emitConstFloat(Floating(F), Info);
8645
8646 APInt I = F.bitcastToAPInt();
8647 return this->emitConstFloat(
8648 Floating(const_cast<uint64_t *>(I.getRawData()),
8649 llvm::APFloatBase::SemanticsToEnum(F.getSemantics())),
8650 Info);
8651}
8652
8653// This function is constexpr if and only if To, From, and the types of
8654// all subobjects of To and From are types T such that...
8655// (3.1) - is_union_v<T> is false;
8656// (3.2) - is_pointer_v<T> is false;
8657// (3.3) - is_member_pointer_v<T> is false;
8658// (3.4) - is_volatile_v<T> is false; and
8659// (3.5) - T has no non-static data members of reference type
8660template <class Emitter>
8661bool Compiler<Emitter>::emitBuiltinBitCast(const CastExpr *E) {
8662 const Expr *SubExpr = E->getSubExpr();
8663 QualType FromType = SubExpr->getType();
8664 QualType ToType = E->getType();
8665 OptPrimType ToT = classify(ToType);
8666
8667 assert(!ToType->isReferenceType());
8668
8669 // Prepare storage for the result in case we discard.
8670 if (DiscardResult && !Initializing && !ToT) {
8671 UnsignedOrNone LocalIndex = allocateLocal(E);
8672 if (!LocalIndex)
8673 return false;
8674 if (!this->emitGetPtrLocal(*LocalIndex, E))
8675 return false;
8676 }
8677
8678 // Get a pointer to the value-to-cast on the stack.
8679 // For CK_LValueToRValueBitCast, this is always an lvalue and
8680 // we later assume it to be one (i.e. a PT_Ptr). However,
8681 // we call this function for other utility methods where
8682 // a bitcast might be useful, so convert it to a PT_Ptr in that case.
8683 if (SubExpr->isGLValue() || FromType->isVectorType()) {
8684 if (!this->visit(SubExpr))
8685 return false;
8686 } else if (OptPrimType FromT = classify(SubExpr)) {
8687 unsigned TempOffset =
8688 allocateLocalPrimitive(SubExpr, *FromT, /*IsConst=*/true);
8689 if (!this->visit(SubExpr))
8690 return false;
8691 if (!this->emitSetLocal(*FromT, TempOffset, E))
8692 return false;
8693 if (!this->emitGetPtrLocal(TempOffset, E))
8694 return false;
8695 } else {
8696 return false;
8697 }
8698
8699 if (!ToT) {
8700 if (!this->emitBitCast(E))
8701 return false;
8702 return DiscardResult ? this->emitPopPtr(E) : true;
8703 }
8704 assert(ToT);
8705
8706 const llvm::fltSemantics *TargetSemantics = nullptr;
8707 if (ToT == PT_Float)
8708 TargetSemantics = &Ctx.getFloatSemantics(ToType);
8709
8710 // Conversion to a primitive type. FromType can be another
8711 // primitive type, or a record/array.
8712 bool ToTypeIsUChar = (ToType->isSpecificBuiltinType(BuiltinType::UChar) ||
8713 ToType->isSpecificBuiltinType(BuiltinType::Char_U));
8714 uint32_t ResultBitWidth = std::max(Ctx.getBitWidth(ToType), 8u);
8715
8716 if (!this->emitBitCastPrim(*ToT, ToTypeIsUChar || ToType->isStdByteType(),
8717 ResultBitWidth, TargetSemantics,
8718 ToType.getTypePtr(), E))
8719 return false;
8720
8721 if (DiscardResult)
8722 return this->emitPop(*ToT, E);
8723
8724 return true;
8725}
8726
8727/// Replicate a scalar value into every scalar element of an aggregate.
8728/// The scalar is stored in a local at \p SrcOffset and a pointer to the
8729/// destination must be on top of the interpreter stack. Each element receives
8730/// the scalar, cast to its own type.
8731template <class Emitter>
8732bool Compiler<Emitter>::emitHLSLAggregateSplat(PrimType SrcT,
8733 unsigned SrcOffset,
8734 QualType DestType,
8735 const Expr *E) {
8736 // Vectors and matrices are treated as flat sequences of elements.
8737 unsigned NumElems = 0;
8738 QualType ElemType;
8739 if (const auto *VT = DestType->getAs<VectorType>()) {
8740 NumElems = VT->getNumElements();
8741 ElemType = VT->getElementType();
8742 } else if (const auto *MT = DestType->getAs<ConstantMatrixType>()) {
8743 NumElems = MT->getNumElementsFlattened();
8744 ElemType = MT->getElementType();
8745 }
8746 if (NumElems > 0) {
8747 PrimType ElemT = classifyPrim(ElemType);
8748 for (unsigned I = 0; I != NumElems; ++I) {
8749 if (!this->emitGetLocal(SrcT, SrcOffset, E))
8750 return false;
8751 if (!this->emitPrimCast(SrcT, ElemT, ElemType, E))
8752 return false;
8753 if (!this->emitInitElem(ElemT, I, E))
8754 return false;
8755 }
8756 return true;
8757 }
8758
8759 // Arrays: primitive elements are filled directly; composite elements
8760 // require recursion into each sub-aggregate.
8761 if (const auto *AT = DestType->getAsArrayTypeUnsafe()) {
8762 const auto *CAT = cast<ConstantArrayType>(AT);
8763 QualType ArrElemType = CAT->getElementType();
8764 unsigned ArrSize = CAT->getZExtSize();
8765
8766 if (OptPrimType ElemT = classify(ArrElemType)) {
8767 for (unsigned I = 0; I != ArrSize; ++I) {
8768 if (!this->emitGetLocal(SrcT, SrcOffset, E))
8769 return false;
8770 if (!this->emitPrimCast(SrcT, *ElemT, ArrElemType, E))
8771 return false;
8772 if (!this->emitInitElem(*ElemT, I, E))
8773 return false;
8774 }
8775 } else {
8776 for (unsigned I = 0; I != ArrSize; ++I) {
8777 if (!this->emitConstUint32(I, E))
8778 return false;
8779 if (!this->emitArrayElemPtrUint32(E))
8780 return false;
8781 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, ArrElemType, E))
8782 return false;
8783 if (!this->emitFinishInitPop(E))
8784 return false;
8785 }
8786 }
8787 return true;
8788 }
8789
8790 // Records: fill base classes first, then named fields in declaration
8791 // order.
8792 if (DestType->isRecordType()) {
8793 const Record *R = getRecord(DestType);
8794 if (!R)
8795 return false;
8796
8797 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
8798 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
8799 const Record::Base *B = R->getBase(BS.getType());
8800 assert(B);
8801 if (!this->emitGetPtrBase(B->Offset, E))
8802 return false;
8803 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, BS.getType(), E))
8804 return false;
8805 if (!this->emitFinishInitPop(E))
8806 return false;
8807 }
8808 }
8809
8810 for (const Record::Field &F : R->fields()) {
8811 if (F.isUnnamedBitField())
8812 continue;
8813
8814 QualType FieldType = F.Decl->getType();
8815 if (OptPrimType FieldT = classify(FieldType)) {
8816 if (!this->emitGetLocal(SrcT, SrcOffset, E))
8817 return false;
8818 if (!this->emitPrimCast(SrcT, *FieldT, FieldType, E))
8819 return false;
8820 if (F.isBitField()) {
8821 if (!this->emitInitBitField(*FieldT, F.Offset, F.bitWidth(), E))
8822 return false;
8823 } else {
8824 if (!this->emitInitField(*FieldT, F.Offset, E))
8825 return false;
8826 }
8827 } else {
8828 if (!this->emitGetPtrField(F.Offset, E))
8829 return false;
8830 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, FieldType, E))
8831 return false;
8832 if (!this->emitPopPtr(E))
8833 return false;
8834 }
8835 }
8836 return true;
8837 }
8838
8839 return false;
8840}
8841
8842/// Return the total number of scalar elements in a type. This is used
8843/// to cap how many source elements are extracted during an elementwise cast,
8844/// so we never flatten more than the destination can hold.
8845template <class Emitter>
8846unsigned Compiler<Emitter>::countHLSLFlatElements(QualType Ty) {
8847 // Vector and matrix types are treated as flat sequences of elements.
8848 if (const auto *VT = Ty->getAs<VectorType>())
8849 return VT->getNumElements();
8850 if (const auto *MT = Ty->getAs<ConstantMatrixType>())
8851 return MT->getNumElementsFlattened();
8852 // Arrays: total count is array size * scalar elements per element.
8853 if (const auto *AT = Ty->getAsArrayTypeUnsafe()) {
8854 const auto *CAT = cast<ConstantArrayType>(AT);
8855 return CAT->getZExtSize() * countHLSLFlatElements(CAT->getElementType());
8856 }
8857 // Records: sum scalar element counts of base classes and named fields.
8858 if (Ty->isRecordType()) {
8859 const Record *R = getRecord(Ty);
8860 if (!R)
8861 return 0;
8862 unsigned Count = 0;
8863 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
8864 for (const CXXBaseSpecifier &BS : CXXRD->bases())
8865 Count += countHLSLFlatElements(BS.getType());
8866 }
8867 for (const Record::Field &F : R->fields()) {
8868 if (F.isUnnamedBitField())
8869 continue;
8870 Count += countHLSLFlatElements(F.Decl->getType());
8871 }
8872 return Count;
8873 }
8874 // Scalar primitive types contribute one element.
8875 if (canClassify(Ty))
8876 return 1;
8877 return 0;
8878}
8879
8880/// Walk a source aggregate and extract every scalar element into its own local
8881/// variable. The results are appended to \p Elements in declaration order,
8882/// stopping once \p MaxElements have been collected. A pointer to the
8883/// source aggregate must be stored in the local at \p SrcOffset.
8884template <class Emitter>
8885bool Compiler<Emitter>::emitHLSLFlattenAggregate(
8886 QualType SrcType, unsigned SrcOffset,
8887 SmallVectorImpl<HLSLFlatElement> &Elements, unsigned MaxElements,
8888 const Expr *E) {
8889
8890 // Save a scalar value from the stack into a new local and record it.
8891 auto saveToLocal = [&](PrimType T) -> bool {
8892 unsigned Offset = allocateLocalPrimitive(E, T, /*IsConst=*/true);
8893 if (!this->emitSetLocal(T, Offset, E))
8894 return false;
8895 Elements.push_back({Offset, T});
8896 return true;
8897 };
8898
8899 // Save a pointer from the stack into a new local for later use.
8900 auto savePtrToLocal = [&]() -> UnsignedOrNone {
8901 unsigned Offset = allocateLocalPrimitive(E, PT_Ptr, /*IsConst=*/true);
8902 if (!this->emitSetLocal(PT_Ptr, Offset, E))
8903 return std::nullopt;
8904 return Offset;
8905 };
8906
8907 // Vectors and matrices are flat sequences of elements.
8908 unsigned NumElems = 0;
8909 QualType ElemType;
8910 if (const auto *VT = SrcType->getAs<VectorType>()) {
8911 NumElems = VT->getNumElements();
8912 ElemType = VT->getElementType();
8913 } else if (const auto *MT = SrcType->getAs<ConstantMatrixType>()) {
8914 NumElems = MT->getNumElementsFlattened();
8915 ElemType = MT->getElementType();
8916 }
8917 if (NumElems > 0) {
8918 PrimType ElemT = classifyPrim(ElemType);
8919 for (unsigned I = 0; I != NumElems && Elements.size() < MaxElements; ++I) {
8920 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
8921 return false;
8922 if (!this->emitArrayElemPop(ElemT, I, E))
8923 return false;
8924 if (!saveToLocal(ElemT))
8925 return false;
8926 }
8927 return true;
8928 }
8929
8930 // Arrays: primitive elements are extracted directly; composite elements
8931 // require recursion into each sub-aggregate.
8932 if (const auto *AT = SrcType->getAsArrayTypeUnsafe()) {
8933 const auto *CAT = cast<ConstantArrayType>(AT);
8934 QualType ArrElemType = CAT->getElementType();
8935 unsigned ArrSize = CAT->getZExtSize();
8936
8937 if (OptPrimType ElemT = classify(ArrElemType)) {
8938 for (unsigned I = 0; I != ArrSize && Elements.size() < MaxElements; ++I) {
8939 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
8940 return false;
8941 if (!this->emitArrayElemPop(*ElemT, I, E))
8942 return false;
8943 if (!saveToLocal(*ElemT))
8944 return false;
8945 }
8946 } else {
8947 for (unsigned I = 0; I != ArrSize && Elements.size() < MaxElements; ++I) {
8948 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
8949 return false;
8950 if (!this->emitConstUint32(I, E))
8951 return false;
8952 if (!this->emitArrayElemPtrPopUint32(E))
8953 return false;
8954 UnsignedOrNone ElemPtrOffset = savePtrToLocal();
8955 if (!ElemPtrOffset)
8956 return false;
8957 if (!emitHLSLFlattenAggregate(ArrElemType, *ElemPtrOffset, Elements,
8958 MaxElements, E))
8959 return false;
8960 }
8961 }
8962 return true;
8963 }
8964
8965 // Records: base classes come first, then named fields in declaration
8966 // order.
8967 if (SrcType->isRecordType()) {
8968 const Record *R = getRecord(SrcType);
8969 if (!R)
8970 return false;
8971
8972 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
8973 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
8974 if (Elements.size() >= MaxElements)
8975 break;
8976 const Record::Base *B = R->getBase(BS.getType());
8977 assert(B);
8978 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
8979 return false;
8980 if (!this->emitGetPtrBasePop(B->Offset, /*NullOK=*/false, E))
8981 return false;
8982 UnsignedOrNone BasePtrOffset = savePtrToLocal();
8983 if (!BasePtrOffset)
8984 return false;
8985 if (!emitHLSLFlattenAggregate(BS.getType(), *BasePtrOffset, Elements,
8986 MaxElements, E))
8987 return false;
8988 }
8989 }
8990
8991 for (const Record::Field &F : R->fields()) {
8992 if (Elements.size() >= MaxElements)
8993 break;
8994 if (F.isUnnamedBitField())
8995 continue;
8996
8997 QualType FieldType = F.Decl->getType();
8998 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
8999 return false;
9000 if (!this->emitGetPtrFieldPop(F.Offset, E))
9001 return false;
9002
9003 if (OptPrimType FieldT = classify(FieldType)) {
9004 if (!this->emitLoadPop(*FieldT, E))
9005 return false;
9006 if (!saveToLocal(*FieldT))
9007 return false;
9008 } else {
9009 UnsignedOrNone FieldPtrOffset = savePtrToLocal();
9010 if (!FieldPtrOffset)
9011 return false;
9012 if (!emitHLSLFlattenAggregate(FieldType, *FieldPtrOffset, Elements,
9013 MaxElements, E))
9014 return false;
9015 }
9016 }
9017 return true;
9018 }
9019
9020 return false;
9021}
9022
9023/// Populate an HLSL aggregate from a flat list of previously extracted source
9024/// elements, casting each to the corresponding destination element type.
9025/// \p ElemIdx tracks the current position in \p Elements and is advanced as
9026/// elements are consumed. A pointer to the destination must be on top of the
9027/// interpreter stack.
9028template <class Emitter>
9029bool Compiler<Emitter>::emitHLSLConstructAggregate(
9030 QualType DestType, ArrayRef<HLSLFlatElement> Elements, unsigned &ElemIdx,
9031 const Expr *E) {
9032
9033 // Consume the next source element, cast it, and leave it on the stack.
9034 auto loadAndCast = [&](PrimType DestT, QualType DestQT) -> bool {
9035 const auto &Src = Elements[ElemIdx++];
9036 if (!this->emitGetLocal(Src.Type, Src.LocalOffset, E))
9037 return false;
9038 return this->emitPrimCast(Src.Type, DestT, DestQT, E);
9039 };
9040
9041 // Vectors and matrices are flat sequences of elements.
9042 unsigned NumElems = 0;
9043 QualType ElemType;
9044 if (const auto *VT = DestType->getAs<VectorType>()) {
9045 NumElems = VT->getNumElements();
9046 ElemType = VT->getElementType();
9047 } else if (const auto *MT = DestType->getAs<ConstantMatrixType>()) {
9048 NumElems = MT->getNumElementsFlattened();
9049 ElemType = MT->getElementType();
9050 }
9051 if (NumElems > 0) {
9052 PrimType DestElemT = classifyPrim(ElemType);
9053 for (unsigned I = 0; I != NumElems; ++I) {
9054 if (!loadAndCast(DestElemT, ElemType))
9055 return false;
9056 if (!this->emitInitElem(DestElemT, I, E))
9057 return false;
9058 }
9059 return true;
9060 }
9061
9062 // Arrays: primitive elements are filled directly; composite elements
9063 // require recursion into each sub-aggregate.
9064 if (const auto *AT = DestType->getAsArrayTypeUnsafe()) {
9065 const auto *CAT = cast<ConstantArrayType>(AT);
9066 QualType ArrElemType = CAT->getElementType();
9067 unsigned ArrSize = CAT->getZExtSize();
9068
9069 if (OptPrimType ElemT = classify(ArrElemType)) {
9070 for (unsigned I = 0; I != ArrSize; ++I) {
9071 if (!loadAndCast(*ElemT, ArrElemType))
9072 return false;
9073 if (!this->emitInitElem(*ElemT, I, E))
9074 return false;
9075 }
9076 } else {
9077 for (unsigned I = 0; I != ArrSize; ++I) {
9078 if (!this->emitConstUint32(I, E))
9079 return false;
9080 if (!this->emitArrayElemPtrUint32(E))
9081 return false;
9082 if (!emitHLSLConstructAggregate(ArrElemType, Elements, ElemIdx, E))
9083 return false;
9084 if (!this->emitFinishInitPop(E))
9085 return false;
9086 }
9087 }
9088 return true;
9089 }
9090
9091 // Records: base classes come first, then named fields in declaration
9092 // order.
9093 if (DestType->isRecordType()) {
9094 const Record *R = getRecord(DestType);
9095 if (!R)
9096 return false;
9097
9098 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
9099 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
9100 const Record::Base *B = R->getBase(BS.getType());
9101 assert(B);
9102 if (!this->emitGetPtrBase(B->Offset, E))
9103 return false;
9104 if (!emitHLSLConstructAggregate(BS.getType(), Elements, ElemIdx, E))
9105 return false;
9106 if (!this->emitFinishInitPop(E))
9107 return false;
9108 }
9109 }
9110
9111 for (const Record::Field &F : R->fields()) {
9112 if (F.isUnnamedBitField())
9113 continue;
9114
9115 QualType FieldType = F.Decl->getType();
9116 if (OptPrimType FieldT = classify(FieldType)) {
9117 if (!loadAndCast(*FieldT, FieldType))
9118 return false;
9119 if (F.isBitField()) {
9120 if (!this->emitInitBitField(*FieldT, F.Offset, F.bitWidth(), E))
9121 return false;
9122 } else {
9123 if (!this->emitInitField(*FieldT, F.Offset, E))
9124 return false;
9125 }
9126 } else {
9127 if (!this->emitGetPtrField(F.Offset, E))
9128 return false;
9129 if (!emitHLSLConstructAggregate(FieldType, Elements, ElemIdx, E))
9130 return false;
9131 if (!this->emitPopPtr(E))
9132 return false;
9133 }
9134 }
9135 return true;
9136 }
9137
9138 return false;
9139}
9140
9141namespace clang {
9142namespace interp {
9143
9144template class Compiler<ByteCodeEmitter>;
9145template class Compiler<EvalEmitter>;
9146
9147} // namespace interp
9148} // 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:3102
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:2784
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2763
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2928
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:3905
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