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