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