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