xref: /llvm-project/clang/lib/AST/ByteCode/Compiler.cpp (revision c712ab829b2050e2ac1652e032fa0786a43a31c0)
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 "Floating.h"
13 #include "Function.h"
14 #include "InterpShared.h"
15 #include "PrimType.h"
16 #include "Program.h"
17 #include "clang/AST/Attr.h"
18 
19 using namespace clang;
20 using namespace clang::interp;
21 
22 using APSInt = llvm::APSInt;
23 
24 namespace clang {
25 namespace interp {
26 
27 /// Scope used to handle temporaries in toplevel variable declarations.
28 template <class Emitter> class DeclScope final : public LocalScope<Emitter> {
29 public:
30   DeclScope(Compiler<Emitter> *Ctx, const ValueDecl *VD)
31       : LocalScope<Emitter>(Ctx, VD), Scope(Ctx->P, VD),
32         OldInitializingDecl(Ctx->InitializingDecl) {
33     Ctx->InitializingDecl = VD;
34     Ctx->InitStack.push_back(InitLink::Decl(VD));
35   }
36 
37   void addExtended(const Scope::Local &Local) override {
38     return this->addLocal(Local);
39   }
40 
41   ~DeclScope() {
42     this->Ctx->InitializingDecl = OldInitializingDecl;
43     this->Ctx->InitStack.pop_back();
44   }
45 
46 private:
47   Program::DeclScope Scope;
48   const ValueDecl *OldInitializingDecl;
49 };
50 
51 /// Scope used to handle initialization methods.
52 template <class Emitter> class OptionScope final {
53 public:
54   /// Root constructor, compiling or discarding primitives.
55   OptionScope(Compiler<Emitter> *Ctx, bool NewDiscardResult,
56               bool NewInitializing)
57       : Ctx(Ctx), OldDiscardResult(Ctx->DiscardResult),
58         OldInitializing(Ctx->Initializing) {
59     Ctx->DiscardResult = NewDiscardResult;
60     Ctx->Initializing = NewInitializing;
61   }
62 
63   ~OptionScope() {
64     Ctx->DiscardResult = OldDiscardResult;
65     Ctx->Initializing = OldInitializing;
66   }
67 
68 private:
69   /// Parent context.
70   Compiler<Emitter> *Ctx;
71   /// Old discard flag to restore.
72   bool OldDiscardResult;
73   bool OldInitializing;
74 };
75 
76 template <class Emitter>
77 bool InitLink::emit(Compiler<Emitter> *Ctx, const Expr *E) const {
78   switch (Kind) {
79   case K_This:
80     return Ctx->emitThis(E);
81   case K_Field:
82     // We're assuming there's a base pointer on the stack already.
83     return Ctx->emitGetPtrFieldPop(Offset, E);
84   case K_Temp:
85     return Ctx->emitGetPtrLocal(Offset, E);
86   case K_Decl:
87     return Ctx->visitDeclRef(D, E);
88   case K_Elem:
89     if (!Ctx->emitConstUint32(Offset, E))
90       return false;
91     return Ctx->emitArrayElemPtrPopUint32(E);
92   default:
93     llvm_unreachable("Unhandled InitLink kind");
94   }
95   return true;
96 }
97 
98 /// Scope managing label targets.
99 template <class Emitter> class LabelScope {
100 public:
101   virtual ~LabelScope() {}
102 
103 protected:
104   LabelScope(Compiler<Emitter> *Ctx) : Ctx(Ctx) {}
105   /// Compiler instance.
106   Compiler<Emitter> *Ctx;
107 };
108 
109 /// Sets the context for break/continue statements.
110 template <class Emitter> class LoopScope final : public LabelScope<Emitter> {
111 public:
112   using LabelTy = typename Compiler<Emitter>::LabelTy;
113   using OptLabelTy = typename Compiler<Emitter>::OptLabelTy;
114 
115   LoopScope(Compiler<Emitter> *Ctx, LabelTy BreakLabel, LabelTy ContinueLabel)
116       : LabelScope<Emitter>(Ctx), OldBreakLabel(Ctx->BreakLabel),
117         OldContinueLabel(Ctx->ContinueLabel),
118         OldBreakVarScope(Ctx->BreakVarScope),
119         OldContinueVarScope(Ctx->ContinueVarScope) {
120     this->Ctx->BreakLabel = BreakLabel;
121     this->Ctx->ContinueLabel = ContinueLabel;
122     this->Ctx->BreakVarScope = this->Ctx->VarScope;
123     this->Ctx->ContinueVarScope = this->Ctx->VarScope;
124   }
125 
126   ~LoopScope() {
127     this->Ctx->BreakLabel = OldBreakLabel;
128     this->Ctx->ContinueLabel = OldContinueLabel;
129     this->Ctx->ContinueVarScope = OldContinueVarScope;
130     this->Ctx->BreakVarScope = OldBreakVarScope;
131   }
132 
133 private:
134   OptLabelTy OldBreakLabel;
135   OptLabelTy OldContinueLabel;
136   VariableScope<Emitter> *OldBreakVarScope;
137   VariableScope<Emitter> *OldContinueVarScope;
138 };
139 
140 // Sets the context for a switch scope, mapping labels.
141 template <class Emitter> class SwitchScope final : public LabelScope<Emitter> {
142 public:
143   using LabelTy = typename Compiler<Emitter>::LabelTy;
144   using OptLabelTy = typename Compiler<Emitter>::OptLabelTy;
145   using CaseMap = typename Compiler<Emitter>::CaseMap;
146 
147   SwitchScope(Compiler<Emitter> *Ctx, CaseMap &&CaseLabels, LabelTy BreakLabel,
148               OptLabelTy DefaultLabel)
149       : LabelScope<Emitter>(Ctx), OldBreakLabel(Ctx->BreakLabel),
150         OldDefaultLabel(this->Ctx->DefaultLabel),
151         OldCaseLabels(std::move(this->Ctx->CaseLabels)),
152         OldLabelVarScope(Ctx->BreakVarScope) {
153     this->Ctx->BreakLabel = BreakLabel;
154     this->Ctx->DefaultLabel = DefaultLabel;
155     this->Ctx->CaseLabels = std::move(CaseLabels);
156     this->Ctx->BreakVarScope = this->Ctx->VarScope;
157   }
158 
159   ~SwitchScope() {
160     this->Ctx->BreakLabel = OldBreakLabel;
161     this->Ctx->DefaultLabel = OldDefaultLabel;
162     this->Ctx->CaseLabels = std::move(OldCaseLabels);
163     this->Ctx->BreakVarScope = OldLabelVarScope;
164   }
165 
166 private:
167   OptLabelTy OldBreakLabel;
168   OptLabelTy OldDefaultLabel;
169   CaseMap OldCaseLabels;
170   VariableScope<Emitter> *OldLabelVarScope;
171 };
172 
173 template <class Emitter> class StmtExprScope final {
174 public:
175   StmtExprScope(Compiler<Emitter> *Ctx) : Ctx(Ctx), OldFlag(Ctx->InStmtExpr) {
176     Ctx->InStmtExpr = true;
177   }
178 
179   ~StmtExprScope() { Ctx->InStmtExpr = OldFlag; }
180 
181 private:
182   Compiler<Emitter> *Ctx;
183   bool OldFlag;
184 };
185 
186 } // namespace interp
187 } // namespace clang
188 
189 template <class Emitter>
190 bool Compiler<Emitter>::VisitCastExpr(const CastExpr *CE) {
191   const Expr *SubExpr = CE->getSubExpr();
192   switch (CE->getCastKind()) {
193 
194   case CK_LValueToRValue: {
195     if (DiscardResult)
196       return this->discard(SubExpr);
197 
198     std::optional<PrimType> SubExprT = classify(SubExpr->getType());
199     // Prepare storage for the result.
200     if (!Initializing && !SubExprT) {
201       std::optional<unsigned> LocalIndex = allocateLocal(SubExpr);
202       if (!LocalIndex)
203         return false;
204       if (!this->emitGetPtrLocal(*LocalIndex, CE))
205         return false;
206     }
207 
208     if (!this->visit(SubExpr))
209       return false;
210 
211     if (SubExprT)
212       return this->emitLoadPop(*SubExprT, CE);
213 
214     // If the subexpr type is not primitive, we need to perform a copy here.
215     // This happens for example in C when dereferencing a pointer of struct
216     // type.
217     return this->emitMemcpy(CE);
218   }
219 
220   case CK_DerivedToBaseMemberPointer: {
221     assert(classifyPrim(CE->getType()) == PT_MemberPtr);
222     assert(classifyPrim(SubExpr->getType()) == PT_MemberPtr);
223     const auto *FromMP = SubExpr->getType()->getAs<MemberPointerType>();
224     const auto *ToMP = CE->getType()->getAs<MemberPointerType>();
225 
226     unsigned DerivedOffset = collectBaseOffset(QualType(ToMP->getClass(), 0),
227                                                QualType(FromMP->getClass(), 0));
228 
229     if (!this->delegate(SubExpr))
230       return false;
231 
232     return this->emitGetMemberPtrBasePop(DerivedOffset, CE);
233   }
234 
235   case CK_BaseToDerivedMemberPointer: {
236     assert(classifyPrim(CE) == PT_MemberPtr);
237     assert(classifyPrim(SubExpr) == PT_MemberPtr);
238     const auto *FromMP = SubExpr->getType()->getAs<MemberPointerType>();
239     const auto *ToMP = CE->getType()->getAs<MemberPointerType>();
240 
241     unsigned DerivedOffset = collectBaseOffset(QualType(FromMP->getClass(), 0),
242                                                QualType(ToMP->getClass(), 0));
243 
244     if (!this->delegate(SubExpr))
245       return false;
246     return this->emitGetMemberPtrBasePop(-DerivedOffset, CE);
247   }
248 
249   case CK_UncheckedDerivedToBase:
250   case CK_DerivedToBase: {
251     if (!this->delegate(SubExpr))
252       return false;
253 
254     const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
255       if (const auto *PT = dyn_cast<PointerType>(Ty))
256         return PT->getPointeeType()->getAsCXXRecordDecl();
257       return Ty->getAsCXXRecordDecl();
258     };
259 
260     // FIXME: We can express a series of non-virtual casts as a single
261     // GetPtrBasePop op.
262     QualType CurType = SubExpr->getType();
263     for (const CXXBaseSpecifier *B : CE->path()) {
264       if (B->isVirtual()) {
265         if (!this->emitGetPtrVirtBasePop(extractRecordDecl(B->getType()), CE))
266           return false;
267         CurType = B->getType();
268       } else {
269         unsigned DerivedOffset = collectBaseOffset(B->getType(), CurType);
270         if (!this->emitGetPtrBasePop(DerivedOffset, CE))
271           return false;
272         CurType = B->getType();
273       }
274     }
275 
276     return true;
277   }
278 
279   case CK_BaseToDerived: {
280     if (!this->delegate(SubExpr))
281       return false;
282 
283     unsigned DerivedOffset =
284         collectBaseOffset(SubExpr->getType(), CE->getType());
285 
286     return this->emitGetPtrDerivedPop(DerivedOffset, CE);
287   }
288 
289   case CK_FloatingCast: {
290     // HLSL uses CK_FloatingCast to cast between vectors.
291     if (!SubExpr->getType()->isFloatingType() ||
292         !CE->getType()->isFloatingType())
293       return false;
294     if (DiscardResult)
295       return this->discard(SubExpr);
296     if (!this->visit(SubExpr))
297       return false;
298     const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType());
299     return this->emitCastFP(TargetSemantics, getRoundingMode(CE), CE);
300   }
301 
302   case CK_IntegralToFloating: {
303     if (DiscardResult)
304       return this->discard(SubExpr);
305     std::optional<PrimType> FromT = classify(SubExpr->getType());
306     if (!FromT)
307       return false;
308 
309     if (!this->visit(SubExpr))
310       return false;
311 
312     const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType());
313     return this->emitCastIntegralFloating(*FromT, TargetSemantics,
314                                           getFPOptions(CE), CE);
315   }
316 
317   case CK_FloatingToBoolean:
318   case CK_FloatingToIntegral: {
319     if (DiscardResult)
320       return this->discard(SubExpr);
321 
322     std::optional<PrimType> ToT = classify(CE->getType());
323 
324     if (!ToT)
325       return false;
326 
327     if (!this->visit(SubExpr))
328       return false;
329 
330     if (ToT == PT_IntAP)
331       return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(CE->getType()),
332                                               getFPOptions(CE), CE);
333     if (ToT == PT_IntAPS)
334       return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(CE->getType()),
335                                                getFPOptions(CE), CE);
336 
337     return this->emitCastFloatingIntegral(*ToT, getFPOptions(CE), CE);
338   }
339 
340   case CK_NullToPointer:
341   case CK_NullToMemberPointer: {
342     if (!this->discard(SubExpr))
343       return false;
344     if (DiscardResult)
345       return true;
346 
347     const Descriptor *Desc = nullptr;
348     const QualType PointeeType = CE->getType()->getPointeeType();
349     if (!PointeeType.isNull()) {
350       if (std::optional<PrimType> T = classify(PointeeType))
351         Desc = P.createDescriptor(SubExpr, *T);
352       else
353         Desc = P.createDescriptor(SubExpr, PointeeType.getTypePtr(),
354                                   std::nullopt, true, false,
355                                   /*IsMutable=*/false, nullptr);
356     }
357     return this->emitNull(classifyPrim(CE->getType()), Desc, CE);
358   }
359 
360   case CK_PointerToIntegral: {
361     if (DiscardResult)
362       return this->discard(SubExpr);
363 
364     if (!this->visit(SubExpr))
365       return false;
366 
367     // If SubExpr doesn't result in a pointer, make it one.
368     if (PrimType FromT = classifyPrim(SubExpr->getType()); FromT != PT_Ptr) {
369       assert(isPtrType(FromT));
370       if (!this->emitDecayPtr(FromT, PT_Ptr, CE))
371         return false;
372     }
373 
374     PrimType T = classifyPrim(CE->getType());
375     if (T == PT_IntAP)
376       return this->emitCastPointerIntegralAP(Ctx.getBitWidth(CE->getType()),
377                                              CE);
378     if (T == PT_IntAPS)
379       return this->emitCastPointerIntegralAPS(Ctx.getBitWidth(CE->getType()),
380                                               CE);
381     return this->emitCastPointerIntegral(T, CE);
382   }
383 
384   case CK_ArrayToPointerDecay: {
385     if (!this->visit(SubExpr))
386       return false;
387     if (!this->emitArrayDecay(CE))
388       return false;
389     if (DiscardResult)
390       return this->emitPopPtr(CE);
391     return true;
392   }
393 
394   case CK_IntegralToPointer: {
395     QualType IntType = SubExpr->getType();
396     assert(IntType->isIntegralOrEnumerationType());
397     if (!this->visit(SubExpr))
398       return false;
399     // FIXME: I think the discard is wrong since the int->ptr cast might cause a
400     // diagnostic.
401     PrimType T = classifyPrim(IntType);
402     if (DiscardResult)
403       return this->emitPop(T, CE);
404 
405     QualType PtrType = CE->getType();
406     const Descriptor *Desc;
407     if (std::optional<PrimType> T = classify(PtrType->getPointeeType()))
408       Desc = P.createDescriptor(SubExpr, *T);
409     else if (PtrType->getPointeeType()->isVoidType())
410       Desc = nullptr;
411     else
412       Desc = P.createDescriptor(CE, PtrType->getPointeeType().getTypePtr(),
413                                 Descriptor::InlineDescMD, true, false,
414                                 /*IsMutable=*/false, nullptr);
415 
416     if (!this->emitGetIntPtr(T, Desc, CE))
417       return false;
418 
419     PrimType DestPtrT = classifyPrim(PtrType);
420     if (DestPtrT == PT_Ptr)
421       return true;
422 
423     // In case we're converting the integer to a non-Pointer.
424     return this->emitDecayPtr(PT_Ptr, DestPtrT, CE);
425   }
426 
427   case CK_AtomicToNonAtomic:
428   case CK_ConstructorConversion:
429   case CK_FunctionToPointerDecay:
430   case CK_NonAtomicToAtomic:
431   case CK_NoOp:
432   case CK_UserDefinedConversion:
433   case CK_AddressSpaceConversion:
434     return this->delegate(SubExpr);
435 
436   case CK_BitCast: {
437     // Reject bitcasts to atomic types.
438     if (CE->getType()->isAtomicType()) {
439       if (!this->discard(SubExpr))
440         return false;
441       return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, CE);
442     }
443 
444     if (DiscardResult)
445       return this->discard(SubExpr);
446 
447     QualType SubExprTy = SubExpr->getType();
448     std::optional<PrimType> FromT = classify(SubExprTy);
449     std::optional<PrimType> ToT = classify(CE->getType());
450     if (!FromT || !ToT)
451       return false;
452 
453     assert(isPtrType(*FromT));
454     assert(isPtrType(*ToT));
455     if (FromT == ToT) {
456       if (CE->getType()->isVoidPointerType())
457         return this->delegate(SubExpr);
458 
459       if (!this->visit(SubExpr))
460         return false;
461       if (FromT == PT_Ptr)
462         return this->emitPtrPtrCast(SubExprTy->isVoidPointerType(), CE);
463       return true;
464     }
465 
466     if (!this->visit(SubExpr))
467       return false;
468     return this->emitDecayPtr(*FromT, *ToT, CE);
469   }
470 
471   case CK_IntegralToBoolean:
472   case CK_BooleanToSignedIntegral:
473   case CK_IntegralCast: {
474     if (DiscardResult)
475       return this->discard(SubExpr);
476     std::optional<PrimType> FromT = classify(SubExpr->getType());
477     std::optional<PrimType> ToT = classify(CE->getType());
478 
479     if (!FromT || !ToT)
480       return false;
481 
482     if (!this->visit(SubExpr))
483       return false;
484 
485     // Possibly diagnose casts to enum types if the target type does not
486     // have a fixed size.
487     if (Ctx.getLangOpts().CPlusPlus && CE->getType()->isEnumeralType()) {
488       if (const auto *ET = CE->getType().getCanonicalType()->getAs<EnumType>();
489           ET && !ET->getDecl()->isFixed()) {
490         if (!this->emitCheckEnumValue(*FromT, ET->getDecl(), CE))
491           return false;
492       }
493     }
494 
495     auto maybeNegate = [&]() -> bool {
496       if (CE->getCastKind() == CK_BooleanToSignedIntegral)
497         return this->emitNeg(*ToT, CE);
498       return true;
499     };
500 
501     if (ToT == PT_IntAP)
502       return this->emitCastAP(*FromT, Ctx.getBitWidth(CE->getType()), CE) &&
503              maybeNegate();
504     if (ToT == PT_IntAPS)
505       return this->emitCastAPS(*FromT, Ctx.getBitWidth(CE->getType()), CE) &&
506              maybeNegate();
507 
508     if (FromT == ToT)
509       return true;
510     if (!this->emitCast(*FromT, *ToT, CE))
511       return false;
512 
513     return maybeNegate();
514   }
515 
516   case CK_PointerToBoolean:
517   case CK_MemberPointerToBoolean: {
518     PrimType PtrT = classifyPrim(SubExpr->getType());
519 
520     if (!this->visit(SubExpr))
521       return false;
522     return this->emitIsNonNull(PtrT, CE);
523   }
524 
525   case CK_IntegralComplexToBoolean:
526   case CK_FloatingComplexToBoolean: {
527     if (DiscardResult)
528       return this->discard(SubExpr);
529     if (!this->visit(SubExpr))
530       return false;
531     return this->emitComplexBoolCast(SubExpr);
532   }
533 
534   case CK_IntegralComplexToReal:
535   case CK_FloatingComplexToReal:
536     return this->emitComplexReal(SubExpr);
537 
538   case CK_IntegralRealToComplex:
539   case CK_FloatingRealToComplex: {
540     // We're creating a complex value here, so we need to
541     // allocate storage for it.
542     if (!Initializing) {
543       unsigned LocalIndex = allocateTemporary(CE);
544       if (!this->emitGetPtrLocal(LocalIndex, CE))
545         return false;
546     }
547 
548     // Init the complex value to {SubExpr, 0}.
549     if (!this->visitArrayElemInit(0, SubExpr))
550       return false;
551     // Zero-init the second element.
552     PrimType T = classifyPrim(SubExpr->getType());
553     if (!this->visitZeroInitializer(T, SubExpr->getType(), SubExpr))
554       return false;
555     return this->emitInitElem(T, 1, SubExpr);
556   }
557 
558   case CK_IntegralComplexCast:
559   case CK_FloatingComplexCast:
560   case CK_IntegralComplexToFloatingComplex:
561   case CK_FloatingComplexToIntegralComplex: {
562     assert(CE->getType()->isAnyComplexType());
563     assert(SubExpr->getType()->isAnyComplexType());
564     if (DiscardResult)
565       return this->discard(SubExpr);
566 
567     if (!Initializing) {
568       std::optional<unsigned> LocalIndex = allocateLocal(CE);
569       if (!LocalIndex)
570         return false;
571       if (!this->emitGetPtrLocal(*LocalIndex, CE))
572         return false;
573     }
574 
575     // Location for the SubExpr.
576     // Since SubExpr is of complex type, visiting it results in a pointer
577     // anyway, so we just create a temporary pointer variable.
578     unsigned SubExprOffset = allocateLocalPrimitive(
579         SubExpr, PT_Ptr, /*IsConst=*/true, /*IsExtended=*/false);
580     if (!this->visit(SubExpr))
581       return false;
582     if (!this->emitSetLocal(PT_Ptr, SubExprOffset, CE))
583       return false;
584 
585     PrimType SourceElemT = classifyComplexElementType(SubExpr->getType());
586     QualType DestElemType =
587         CE->getType()->getAs<ComplexType>()->getElementType();
588     PrimType DestElemT = classifyPrim(DestElemType);
589     // Cast both elements individually.
590     for (unsigned I = 0; I != 2; ++I) {
591       if (!this->emitGetLocal(PT_Ptr, SubExprOffset, CE))
592         return false;
593       if (!this->emitArrayElemPop(SourceElemT, I, CE))
594         return false;
595 
596       // Do the cast.
597       if (!this->emitPrimCast(SourceElemT, DestElemT, DestElemType, CE))
598         return false;
599 
600       // Save the value.
601       if (!this->emitInitElem(DestElemT, I, CE))
602         return false;
603     }
604     return true;
605   }
606 
607   case CK_VectorSplat: {
608     assert(!classify(CE->getType()));
609     assert(classify(SubExpr->getType()));
610     assert(CE->getType()->isVectorType());
611 
612     if (DiscardResult)
613       return this->discard(SubExpr);
614 
615     if (!Initializing) {
616       std::optional<unsigned> LocalIndex = allocateLocal(CE);
617       if (!LocalIndex)
618         return false;
619       if (!this->emitGetPtrLocal(*LocalIndex, CE))
620         return false;
621     }
622 
623     const auto *VT = CE->getType()->getAs<VectorType>();
624     PrimType ElemT = classifyPrim(SubExpr->getType());
625     unsigned ElemOffset = allocateLocalPrimitive(
626         SubExpr, ElemT, /*IsConst=*/true, /*IsExtended=*/false);
627 
628     // Prepare a local variable for the scalar value.
629     if (!this->visit(SubExpr))
630       return false;
631     if (classifyPrim(SubExpr) == PT_Ptr && !this->emitLoadPop(ElemT, CE))
632       return false;
633 
634     if (!this->emitSetLocal(ElemT, ElemOffset, CE))
635       return false;
636 
637     for (unsigned I = 0; I != VT->getNumElements(); ++I) {
638       if (!this->emitGetLocal(ElemT, ElemOffset, CE))
639         return false;
640       if (!this->emitInitElem(ElemT, I, CE))
641         return false;
642     }
643 
644     return true;
645   }
646 
647   case CK_HLSLVectorTruncation: {
648     assert(SubExpr->getType()->isVectorType());
649     if (std::optional<PrimType> ResultT = classify(CE)) {
650       assert(!DiscardResult);
651       // Result must be either a float or integer. Take the first element.
652       if (!this->visit(SubExpr))
653         return false;
654       return this->emitArrayElemPop(*ResultT, 0, CE);
655     }
656     // Otherwise, this truncates from one vector type to another.
657     assert(CE->getType()->isVectorType());
658 
659     if (!Initializing) {
660       unsigned LocalIndex = allocateTemporary(CE);
661       if (!this->emitGetPtrLocal(LocalIndex, CE))
662         return false;
663     }
664     unsigned ToSize = CE->getType()->getAs<VectorType>()->getNumElements();
665     assert(SubExpr->getType()->getAs<VectorType>()->getNumElements() > ToSize);
666     if (!this->visit(SubExpr))
667       return false;
668     return this->emitCopyArray(classifyVectorElementType(CE->getType()), 0, 0,
669                                ToSize, CE);
670   };
671 
672   case CK_ToVoid:
673     return discard(SubExpr);
674 
675   default:
676     return this->emitInvalid(CE);
677   }
678   llvm_unreachable("Unhandled clang::CastKind enum");
679 }
680 
681 template <class Emitter>
682 bool Compiler<Emitter>::VisitIntegerLiteral(const IntegerLiteral *LE) {
683   if (DiscardResult)
684     return true;
685 
686   return this->emitConst(LE->getValue(), LE);
687 }
688 
689 template <class Emitter>
690 bool Compiler<Emitter>::VisitFloatingLiteral(const FloatingLiteral *E) {
691   if (DiscardResult)
692     return true;
693 
694   return this->emitConstFloat(E->getValue(), E);
695 }
696 
697 template <class Emitter>
698 bool Compiler<Emitter>::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
699   assert(E->getType()->isAnyComplexType());
700   if (DiscardResult)
701     return true;
702 
703   if (!Initializing) {
704     unsigned LocalIndex = allocateTemporary(E);
705     if (!this->emitGetPtrLocal(LocalIndex, E))
706       return false;
707   }
708 
709   const Expr *SubExpr = E->getSubExpr();
710   PrimType SubExprT = classifyPrim(SubExpr->getType());
711 
712   if (!this->visitZeroInitializer(SubExprT, SubExpr->getType(), SubExpr))
713     return false;
714   if (!this->emitInitElem(SubExprT, 0, SubExpr))
715     return false;
716   return this->visitArrayElemInit(1, SubExpr);
717 }
718 
719 template <class Emitter>
720 bool Compiler<Emitter>::VisitParenExpr(const ParenExpr *E) {
721   return this->delegate(E->getSubExpr());
722 }
723 
724 template <class Emitter>
725 bool Compiler<Emitter>::VisitBinaryOperator(const BinaryOperator *BO) {
726   // Need short-circuiting for these.
727   if (BO->getType()->isVectorType())
728     return this->VisitVectorBinOp(BO);
729   if (BO->isLogicalOp())
730     return this->VisitLogicalBinOp(BO);
731 
732   const Expr *LHS = BO->getLHS();
733   const Expr *RHS = BO->getRHS();
734 
735   // Handle comma operators. Just discard the LHS
736   // and delegate to RHS.
737   if (BO->isCommaOp()) {
738     if (!this->discard(LHS))
739       return false;
740     if (RHS->getType()->isVoidType())
741       return this->discard(RHS);
742 
743     return this->delegate(RHS);
744   }
745 
746   if (BO->getType()->isAnyComplexType())
747     return this->VisitComplexBinOp(BO);
748   if ((LHS->getType()->isAnyComplexType() ||
749        RHS->getType()->isAnyComplexType()) &&
750       BO->isComparisonOp())
751     return this->emitComplexComparison(LHS, RHS, BO);
752 
753   if (BO->isPtrMemOp()) {
754     if (!this->visit(LHS))
755       return false;
756 
757     if (!this->visit(RHS))
758       return false;
759 
760     if (!this->emitToMemberPtr(BO))
761       return false;
762 
763     if (classifyPrim(BO) == PT_MemberPtr)
764       return true;
765 
766     if (!this->emitCastMemberPtrPtr(BO))
767       return false;
768     return DiscardResult ? this->emitPopPtr(BO) : true;
769   }
770 
771   // Typecheck the args.
772   std::optional<PrimType> LT = classify(LHS);
773   std::optional<PrimType> RT = classify(RHS);
774   std::optional<PrimType> T = classify(BO->getType());
775 
776   // Special case for C++'s three-way/spaceship operator <=>, which
777   // returns a std::{strong,weak,partial}_ordering (which is a class, so doesn't
778   // have a PrimType).
779   if (!T && BO->getOpcode() == BO_Cmp) {
780     if (DiscardResult)
781       return true;
782     const ComparisonCategoryInfo *CmpInfo =
783         Ctx.getASTContext().CompCategories.lookupInfoForType(BO->getType());
784     assert(CmpInfo);
785 
786     // We need a temporary variable holding our return value.
787     if (!Initializing) {
788       std::optional<unsigned> ResultIndex = this->allocateLocal(BO);
789       if (!this->emitGetPtrLocal(*ResultIndex, BO))
790         return false;
791     }
792 
793     if (!visit(LHS) || !visit(RHS))
794       return false;
795 
796     return this->emitCMP3(*LT, CmpInfo, BO);
797   }
798 
799   if (!LT || !RT || !T)
800     return false;
801 
802   // Pointer arithmetic special case.
803   if (BO->getOpcode() == BO_Add || BO->getOpcode() == BO_Sub) {
804     if (isPtrType(*T) || (isPtrType(*LT) && isPtrType(*RT)))
805       return this->VisitPointerArithBinOp(BO);
806   }
807 
808   // Assignmentes require us to evalute the RHS first.
809   if (BO->getOpcode() == BO_Assign) {
810     if (!visit(RHS) || !visit(LHS))
811       return false;
812     if (!this->emitFlip(*LT, *RT, BO))
813       return false;
814   } else {
815     if (!visit(LHS) || !visit(RHS))
816       return false;
817   }
818 
819   // For languages such as C, cast the result of one
820   // of our comparision opcodes to T (which is usually int).
821   auto MaybeCastToBool = [this, T, BO](bool Result) {
822     if (!Result)
823       return false;
824     if (DiscardResult)
825       return this->emitPop(*T, BO);
826     if (T != PT_Bool)
827       return this->emitCast(PT_Bool, *T, BO);
828     return true;
829   };
830 
831   auto Discard = [this, T, BO](bool Result) {
832     if (!Result)
833       return false;
834     return DiscardResult ? this->emitPop(*T, BO) : true;
835   };
836 
837   switch (BO->getOpcode()) {
838   case BO_EQ:
839     return MaybeCastToBool(this->emitEQ(*LT, BO));
840   case BO_NE:
841     return MaybeCastToBool(this->emitNE(*LT, BO));
842   case BO_LT:
843     return MaybeCastToBool(this->emitLT(*LT, BO));
844   case BO_LE:
845     return MaybeCastToBool(this->emitLE(*LT, BO));
846   case BO_GT:
847     return MaybeCastToBool(this->emitGT(*LT, BO));
848   case BO_GE:
849     return MaybeCastToBool(this->emitGE(*LT, BO));
850   case BO_Sub:
851     if (BO->getType()->isFloatingType())
852       return Discard(this->emitSubf(getFPOptions(BO), BO));
853     return Discard(this->emitSub(*T, BO));
854   case BO_Add:
855     if (BO->getType()->isFloatingType())
856       return Discard(this->emitAddf(getFPOptions(BO), BO));
857     return Discard(this->emitAdd(*T, BO));
858   case BO_Mul:
859     if (BO->getType()->isFloatingType())
860       return Discard(this->emitMulf(getFPOptions(BO), BO));
861     return Discard(this->emitMul(*T, BO));
862   case BO_Rem:
863     return Discard(this->emitRem(*T, BO));
864   case BO_Div:
865     if (BO->getType()->isFloatingType())
866       return Discard(this->emitDivf(getFPOptions(BO), BO));
867     return Discard(this->emitDiv(*T, BO));
868   case BO_Assign:
869     if (DiscardResult)
870       return LHS->refersToBitField() ? this->emitStoreBitFieldPop(*T, BO)
871                                      : this->emitStorePop(*T, BO);
872     if (LHS->refersToBitField()) {
873       if (!this->emitStoreBitField(*T, BO))
874         return false;
875     } else {
876       if (!this->emitStore(*T, BO))
877         return false;
878     }
879     // Assignments aren't necessarily lvalues in C.
880     // Load from them in that case.
881     if (!BO->isLValue())
882       return this->emitLoadPop(*T, BO);
883     return true;
884   case BO_And:
885     return Discard(this->emitBitAnd(*T, BO));
886   case BO_Or:
887     return Discard(this->emitBitOr(*T, BO));
888   case BO_Shl:
889     return Discard(this->emitShl(*LT, *RT, BO));
890   case BO_Shr:
891     return Discard(this->emitShr(*LT, *RT, BO));
892   case BO_Xor:
893     return Discard(this->emitBitXor(*T, BO));
894   case BO_LOr:
895   case BO_LAnd:
896     llvm_unreachable("Already handled earlier");
897   default:
898     return false;
899   }
900 
901   llvm_unreachable("Unhandled binary op");
902 }
903 
904 /// Perform addition/subtraction of a pointer and an integer or
905 /// subtraction of two pointers.
906 template <class Emitter>
907 bool Compiler<Emitter>::VisitPointerArithBinOp(const BinaryOperator *E) {
908   BinaryOperatorKind Op = E->getOpcode();
909   const Expr *LHS = E->getLHS();
910   const Expr *RHS = E->getRHS();
911 
912   if ((Op != BO_Add && Op != BO_Sub) ||
913       (!LHS->getType()->isPointerType() && !RHS->getType()->isPointerType()))
914     return false;
915 
916   std::optional<PrimType> LT = classify(LHS);
917   std::optional<PrimType> RT = classify(RHS);
918 
919   if (!LT || !RT)
920     return false;
921 
922   // Visit the given pointer expression and optionally convert to a PT_Ptr.
923   auto visitAsPointer = [&](const Expr *E, PrimType T) -> bool {
924     if (!this->visit(E))
925       return false;
926     if (T != PT_Ptr)
927       return this->emitDecayPtr(T, PT_Ptr, E);
928     return true;
929   };
930 
931   if (LHS->getType()->isPointerType() && RHS->getType()->isPointerType()) {
932     if (Op != BO_Sub)
933       return false;
934 
935     assert(E->getType()->isIntegerType());
936     if (!visitAsPointer(RHS, *RT) || !visitAsPointer(LHS, *LT))
937       return false;
938 
939     return this->emitSubPtr(classifyPrim(E->getType()), E);
940   }
941 
942   PrimType OffsetType;
943   if (LHS->getType()->isIntegerType()) {
944     if (!visitAsPointer(RHS, *RT))
945       return false;
946     if (!this->visit(LHS))
947       return false;
948     OffsetType = *LT;
949   } else if (RHS->getType()->isIntegerType()) {
950     if (!visitAsPointer(LHS, *LT))
951       return false;
952     if (!this->visit(RHS))
953       return false;
954     OffsetType = *RT;
955   } else {
956     return false;
957   }
958 
959   // Do the operation and optionally transform to
960   // result pointer type.
961   if (Op == BO_Add) {
962     if (!this->emitAddOffset(OffsetType, E))
963       return false;
964 
965     if (classifyPrim(E) != PT_Ptr)
966       return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E);
967     return true;
968   } else if (Op == BO_Sub) {
969     if (!this->emitSubOffset(OffsetType, E))
970       return false;
971 
972     if (classifyPrim(E) != PT_Ptr)
973       return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E);
974     return true;
975   }
976 
977   return false;
978 }
979 
980 template <class Emitter>
981 bool Compiler<Emitter>::VisitLogicalBinOp(const BinaryOperator *E) {
982   assert(E->isLogicalOp());
983   BinaryOperatorKind Op = E->getOpcode();
984   const Expr *LHS = E->getLHS();
985   const Expr *RHS = E->getRHS();
986   std::optional<PrimType> T = classify(E->getType());
987 
988   if (Op == BO_LOr) {
989     // Logical OR. Visit LHS and only evaluate RHS if LHS was FALSE.
990     LabelTy LabelTrue = this->getLabel();
991     LabelTy LabelEnd = this->getLabel();
992 
993     if (!this->visitBool(LHS))
994       return false;
995     if (!this->jumpTrue(LabelTrue))
996       return false;
997 
998     if (!this->visitBool(RHS))
999       return false;
1000     if (!this->jump(LabelEnd))
1001       return false;
1002 
1003     this->emitLabel(LabelTrue);
1004     this->emitConstBool(true, E);
1005     this->fallthrough(LabelEnd);
1006     this->emitLabel(LabelEnd);
1007 
1008   } else {
1009     assert(Op == BO_LAnd);
1010     // Logical AND.
1011     // Visit LHS. Only visit RHS if LHS was TRUE.
1012     LabelTy LabelFalse = this->getLabel();
1013     LabelTy LabelEnd = this->getLabel();
1014 
1015     if (!this->visitBool(LHS))
1016       return false;
1017     if (!this->jumpFalse(LabelFalse))
1018       return false;
1019 
1020     if (!this->visitBool(RHS))
1021       return false;
1022     if (!this->jump(LabelEnd))
1023       return false;
1024 
1025     this->emitLabel(LabelFalse);
1026     this->emitConstBool(false, E);
1027     this->fallthrough(LabelEnd);
1028     this->emitLabel(LabelEnd);
1029   }
1030 
1031   if (DiscardResult)
1032     return this->emitPopBool(E);
1033 
1034   // For C, cast back to integer type.
1035   assert(T);
1036   if (T != PT_Bool)
1037     return this->emitCast(PT_Bool, *T, E);
1038   return true;
1039 }
1040 
1041 template <class Emitter>
1042 bool Compiler<Emitter>::VisitComplexBinOp(const BinaryOperator *E) {
1043   // Prepare storage for result.
1044   if (!Initializing) {
1045     unsigned LocalIndex = allocateTemporary(E);
1046     if (!this->emitGetPtrLocal(LocalIndex, E))
1047       return false;
1048   }
1049 
1050   // Both LHS and RHS might _not_ be of complex type, but one of them
1051   // needs to be.
1052   const Expr *LHS = E->getLHS();
1053   const Expr *RHS = E->getRHS();
1054 
1055   PrimType ResultElemT = this->classifyComplexElementType(E->getType());
1056   unsigned ResultOffset = ~0u;
1057   if (!DiscardResult)
1058     ResultOffset = this->allocateLocalPrimitive(E, PT_Ptr, true, false);
1059 
1060   // Save result pointer in ResultOffset
1061   if (!this->DiscardResult) {
1062     if (!this->emitDupPtr(E))
1063       return false;
1064     if (!this->emitSetLocal(PT_Ptr, ResultOffset, E))
1065       return false;
1066   }
1067   QualType LHSType = LHS->getType();
1068   if (const auto *AT = LHSType->getAs<AtomicType>())
1069     LHSType = AT->getValueType();
1070   QualType RHSType = RHS->getType();
1071   if (const auto *AT = RHSType->getAs<AtomicType>())
1072     RHSType = AT->getValueType();
1073 
1074   bool LHSIsComplex = LHSType->isAnyComplexType();
1075   unsigned LHSOffset;
1076   bool RHSIsComplex = RHSType->isAnyComplexType();
1077 
1078   // For ComplexComplex Mul, we have special ops to make their implementation
1079   // easier.
1080   BinaryOperatorKind Op = E->getOpcode();
1081   if (Op == BO_Mul && LHSIsComplex && RHSIsComplex) {
1082     assert(classifyPrim(LHSType->getAs<ComplexType>()->getElementType()) ==
1083            classifyPrim(RHSType->getAs<ComplexType>()->getElementType()));
1084     PrimType ElemT =
1085         classifyPrim(LHSType->getAs<ComplexType>()->getElementType());
1086     if (!this->visit(LHS))
1087       return false;
1088     if (!this->visit(RHS))
1089       return false;
1090     return this->emitMulc(ElemT, E);
1091   }
1092 
1093   if (Op == BO_Div && RHSIsComplex) {
1094     QualType ElemQT = RHSType->getAs<ComplexType>()->getElementType();
1095     PrimType ElemT = classifyPrim(ElemQT);
1096     // If the LHS is not complex, we still need to do the full complex
1097     // division, so just stub create a complex value and stub it out with
1098     // the LHS and a zero.
1099 
1100     if (!LHSIsComplex) {
1101       // This is using the RHS type for the fake-complex LHS.
1102       LHSOffset = allocateTemporary(RHS);
1103 
1104       if (!this->emitGetPtrLocal(LHSOffset, E))
1105         return false;
1106 
1107       if (!this->visit(LHS))
1108         return false;
1109       // real is LHS
1110       if (!this->emitInitElem(ElemT, 0, E))
1111         return false;
1112       // imag is zero
1113       if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1114         return false;
1115       if (!this->emitInitElem(ElemT, 1, E))
1116         return false;
1117     } else {
1118       if (!this->visit(LHS))
1119         return false;
1120     }
1121 
1122     if (!this->visit(RHS))
1123       return false;
1124     return this->emitDivc(ElemT, E);
1125   }
1126 
1127   // Evaluate LHS and save value to LHSOffset.
1128   if (LHSType->isAnyComplexType()) {
1129     LHSOffset = this->allocateLocalPrimitive(LHS, PT_Ptr, true, false);
1130     if (!this->visit(LHS))
1131       return false;
1132     if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
1133       return false;
1134   } else {
1135     PrimType LHST = classifyPrim(LHSType);
1136     LHSOffset = this->allocateLocalPrimitive(LHS, LHST, true, false);
1137     if (!this->visit(LHS))
1138       return false;
1139     if (!this->emitSetLocal(LHST, LHSOffset, E))
1140       return false;
1141   }
1142 
1143   // Same with RHS.
1144   unsigned RHSOffset;
1145   if (RHSType->isAnyComplexType()) {
1146     RHSOffset = this->allocateLocalPrimitive(RHS, PT_Ptr, true, false);
1147     if (!this->visit(RHS))
1148       return false;
1149     if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
1150       return false;
1151   } else {
1152     PrimType RHST = classifyPrim(RHSType);
1153     RHSOffset = this->allocateLocalPrimitive(RHS, RHST, true, false);
1154     if (!this->visit(RHS))
1155       return false;
1156     if (!this->emitSetLocal(RHST, RHSOffset, E))
1157       return false;
1158   }
1159 
1160   // For both LHS and RHS, either load the value from the complex pointer, or
1161   // directly from the local variable. For index 1 (i.e. the imaginary part),
1162   // just load 0 and do the operation anyway.
1163   auto loadComplexValue = [this](bool IsComplex, bool LoadZero,
1164                                  unsigned ElemIndex, unsigned Offset,
1165                                  const Expr *E) -> bool {
1166     if (IsComplex) {
1167       if (!this->emitGetLocal(PT_Ptr, Offset, E))
1168         return false;
1169       return this->emitArrayElemPop(classifyComplexElementType(E->getType()),
1170                                     ElemIndex, E);
1171     }
1172     if (ElemIndex == 0 || !LoadZero)
1173       return this->emitGetLocal(classifyPrim(E->getType()), Offset, E);
1174     return this->visitZeroInitializer(classifyPrim(E->getType()), E->getType(),
1175                                       E);
1176   };
1177 
1178   // Now we can get pointers to the LHS and RHS from the offsets above.
1179   for (unsigned ElemIndex = 0; ElemIndex != 2; ++ElemIndex) {
1180     // Result pointer for the store later.
1181     if (!this->DiscardResult) {
1182       if (!this->emitGetLocal(PT_Ptr, ResultOffset, E))
1183         return false;
1184     }
1185 
1186     // The actual operation.
1187     switch (Op) {
1188     case BO_Add:
1189       if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS))
1190         return false;
1191 
1192       if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS))
1193         return false;
1194       if (ResultElemT == PT_Float) {
1195         if (!this->emitAddf(getFPOptions(E), E))
1196           return false;
1197       } else {
1198         if (!this->emitAdd(ResultElemT, E))
1199           return false;
1200       }
1201       break;
1202     case BO_Sub:
1203       if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS))
1204         return false;
1205 
1206       if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS))
1207         return false;
1208       if (ResultElemT == PT_Float) {
1209         if (!this->emitSubf(getFPOptions(E), E))
1210           return false;
1211       } else {
1212         if (!this->emitSub(ResultElemT, E))
1213           return false;
1214       }
1215       break;
1216     case BO_Mul:
1217       if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS))
1218         return false;
1219 
1220       if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS))
1221         return false;
1222 
1223       if (ResultElemT == PT_Float) {
1224         if (!this->emitMulf(getFPOptions(E), E))
1225           return false;
1226       } else {
1227         if (!this->emitMul(ResultElemT, E))
1228           return false;
1229       }
1230       break;
1231     case BO_Div:
1232       assert(!RHSIsComplex);
1233       if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS))
1234         return false;
1235 
1236       if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS))
1237         return false;
1238 
1239       if (ResultElemT == PT_Float) {
1240         if (!this->emitDivf(getFPOptions(E), E))
1241           return false;
1242       } else {
1243         if (!this->emitDiv(ResultElemT, E))
1244           return false;
1245       }
1246       break;
1247 
1248     default:
1249       return false;
1250     }
1251 
1252     if (!this->DiscardResult) {
1253       // Initialize array element with the value we just computed.
1254       if (!this->emitInitElemPop(ResultElemT, ElemIndex, E))
1255         return false;
1256     } else {
1257       if (!this->emitPop(ResultElemT, E))
1258         return false;
1259     }
1260   }
1261   return true;
1262 }
1263 
1264 template <class Emitter>
1265 bool Compiler<Emitter>::VisitVectorBinOp(const BinaryOperator *E) {
1266   assert(E->getType()->isVectorType());
1267   assert(E->getLHS()->getType()->isVectorType());
1268   assert(E->getRHS()->getType()->isVectorType());
1269 
1270   // Prepare storage for result.
1271   if (!Initializing && !E->isCompoundAssignmentOp()) {
1272     unsigned LocalIndex = allocateTemporary(E);
1273     if (!this->emitGetPtrLocal(LocalIndex, E))
1274       return false;
1275   }
1276 
1277   const Expr *LHS = E->getLHS();
1278   const Expr *RHS = E->getRHS();
1279   const auto *VecTy = E->getType()->getAs<VectorType>();
1280   auto Op = E->isCompoundAssignmentOp()
1281                 ? BinaryOperator::getOpForCompoundAssignment(E->getOpcode())
1282                 : E->getOpcode();
1283 
1284   // The LHS and RHS of a comparison operator must have the same type. So we
1285   // just use LHS vector element type here.
1286   PrimType ElemT = this->classifyVectorElementType(LHS->getType());
1287   PrimType ResultElemT = this->classifyVectorElementType(E->getType());
1288 
1289   // Evaluate LHS and save value to LHSOffset.
1290   unsigned LHSOffset = this->allocateLocalPrimitive(LHS, PT_Ptr, true, false);
1291   if (!this->visit(LHS))
1292     return false;
1293   if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
1294     return false;
1295 
1296   // Evaluate RHS and save value to RHSOffset.
1297   unsigned RHSOffset = this->allocateLocalPrimitive(RHS, PT_Ptr, true, false);
1298   if (!this->visit(RHS))
1299     return false;
1300   if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
1301     return false;
1302 
1303   if (E->isCompoundAssignmentOp() && !this->emitGetLocal(PT_Ptr, LHSOffset, E))
1304     return false;
1305 
1306   // BitAdd/BitOr/BitXor/Shl/Shr doesn't support bool type, we need perform the
1307   // integer promotion.
1308   bool NeedIntPromot = ElemT == PT_Bool && (E->isBitwiseOp() || E->isShiftOp());
1309   QualType PromotTy =
1310       Ctx.getASTContext().getPromotedIntegerType(Ctx.getASTContext().BoolTy);
1311   PrimType PromotT = classifyPrim(PromotTy);
1312   PrimType OpT = NeedIntPromot ? PromotT : ElemT;
1313 
1314   auto getElem = [=](unsigned Offset, unsigned Index) {
1315     if (!this->emitGetLocal(PT_Ptr, Offset, E))
1316       return false;
1317     if (!this->emitArrayElemPop(ElemT, Index, E))
1318       return false;
1319     if (E->isLogicalOp()) {
1320       if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
1321         return false;
1322       if (!this->emitPrimCast(PT_Bool, ResultElemT, VecTy->getElementType(), E))
1323         return false;
1324     } else if (NeedIntPromot) {
1325       if (!this->emitPrimCast(ElemT, PromotT, PromotTy, E))
1326         return false;
1327     }
1328     return true;
1329   };
1330 
1331 #define EMIT_ARITH_OP(OP)                                                      \
1332   {                                                                            \
1333     if (ElemT == PT_Float) {                                                   \
1334       if (!this->emit##OP##f(getFPOptions(E), E))                              \
1335         return false;                                                          \
1336     } else {                                                                   \
1337       if (!this->emit##OP(ElemT, E))                                           \
1338         return false;                                                          \
1339     }                                                                          \
1340     break;                                                                     \
1341   }
1342 
1343   for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
1344     if (!getElem(LHSOffset, I))
1345       return false;
1346     if (!getElem(RHSOffset, I))
1347       return false;
1348     switch (Op) {
1349     case BO_Add:
1350       EMIT_ARITH_OP(Add)
1351     case BO_Sub:
1352       EMIT_ARITH_OP(Sub)
1353     case BO_Mul:
1354       EMIT_ARITH_OP(Mul)
1355     case BO_Div:
1356       EMIT_ARITH_OP(Div)
1357     case BO_Rem:
1358       if (!this->emitRem(ElemT, E))
1359         return false;
1360       break;
1361     case BO_And:
1362       if (!this->emitBitAnd(OpT, E))
1363         return false;
1364       break;
1365     case BO_Or:
1366       if (!this->emitBitOr(OpT, E))
1367         return false;
1368       break;
1369     case BO_Xor:
1370       if (!this->emitBitXor(OpT, E))
1371         return false;
1372       break;
1373     case BO_Shl:
1374       if (!this->emitShl(OpT, ElemT, E))
1375         return false;
1376       break;
1377     case BO_Shr:
1378       if (!this->emitShr(OpT, ElemT, E))
1379         return false;
1380       break;
1381     case BO_EQ:
1382       if (!this->emitEQ(ElemT, E))
1383         return false;
1384       break;
1385     case BO_NE:
1386       if (!this->emitNE(ElemT, E))
1387         return false;
1388       break;
1389     case BO_LE:
1390       if (!this->emitLE(ElemT, E))
1391         return false;
1392       break;
1393     case BO_LT:
1394       if (!this->emitLT(ElemT, E))
1395         return false;
1396       break;
1397     case BO_GE:
1398       if (!this->emitGE(ElemT, E))
1399         return false;
1400       break;
1401     case BO_GT:
1402       if (!this->emitGT(ElemT, E))
1403         return false;
1404       break;
1405     case BO_LAnd:
1406       // a && b is equivalent to a!=0 & b!=0
1407       if (!this->emitBitAnd(ResultElemT, E))
1408         return false;
1409       break;
1410     case BO_LOr:
1411       // a || b is equivalent to a!=0 | b!=0
1412       if (!this->emitBitOr(ResultElemT, E))
1413         return false;
1414       break;
1415     default:
1416       return this->emitInvalid(E);
1417     }
1418 
1419     // The result of the comparison is a vector of the same width and number
1420     // of elements as the comparison operands with a signed integral element
1421     // type.
1422     //
1423     // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html
1424     if (E->isComparisonOp()) {
1425       if (!this->emitPrimCast(PT_Bool, ResultElemT, VecTy->getElementType(), E))
1426         return false;
1427       if (!this->emitNeg(ResultElemT, E))
1428         return false;
1429     }
1430 
1431     // If we performed an integer promotion, we need to cast the compute result
1432     // into result vector element type.
1433     if (NeedIntPromot &&
1434         !this->emitPrimCast(PromotT, ResultElemT, VecTy->getElementType(), E))
1435       return false;
1436 
1437     // Initialize array element with the value we just computed.
1438     if (!this->emitInitElem(ResultElemT, I, E))
1439       return false;
1440   }
1441 
1442   if (DiscardResult && E->isCompoundAssignmentOp() && !this->emitPopPtr(E))
1443     return false;
1444   return true;
1445 }
1446 
1447 template <class Emitter>
1448 bool Compiler<Emitter>::VisitImplicitValueInitExpr(
1449     const ImplicitValueInitExpr *E) {
1450   QualType QT = E->getType();
1451 
1452   if (std::optional<PrimType> T = classify(QT))
1453     return this->visitZeroInitializer(*T, QT, E);
1454 
1455   if (QT->isRecordType()) {
1456     const RecordDecl *RD = QT->getAsRecordDecl();
1457     assert(RD);
1458     if (RD->isInvalidDecl())
1459       return false;
1460 
1461     if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1462         CXXRD && CXXRD->getNumVBases() > 0) {
1463       // TODO: Diagnose.
1464       return false;
1465     }
1466 
1467     const Record *R = getRecord(QT);
1468     if (!R)
1469       return false;
1470 
1471     assert(Initializing);
1472     return this->visitZeroRecordInitializer(R, E);
1473   }
1474 
1475   if (QT->isIncompleteArrayType())
1476     return true;
1477 
1478   if (QT->isArrayType()) {
1479     const ArrayType *AT = QT->getAsArrayTypeUnsafe();
1480     assert(AT);
1481     const auto *CAT = cast<ConstantArrayType>(AT);
1482     size_t NumElems = CAT->getZExtSize();
1483     PrimType ElemT = classifyPrim(CAT->getElementType());
1484 
1485     for (size_t I = 0; I != NumElems; ++I) {
1486       if (!this->visitZeroInitializer(ElemT, CAT->getElementType(), E))
1487         return false;
1488       if (!this->emitInitElem(ElemT, I, E))
1489         return false;
1490     }
1491 
1492     return true;
1493   }
1494 
1495   if (const auto *ComplexTy = E->getType()->getAs<ComplexType>()) {
1496     assert(Initializing);
1497     QualType ElemQT = ComplexTy->getElementType();
1498     PrimType ElemT = classifyPrim(ElemQT);
1499     for (unsigned I = 0; I < 2; ++I) {
1500       if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1501         return false;
1502       if (!this->emitInitElem(ElemT, I, E))
1503         return false;
1504     }
1505     return true;
1506   }
1507 
1508   if (const auto *VecT = E->getType()->getAs<VectorType>()) {
1509     unsigned NumVecElements = VecT->getNumElements();
1510     QualType ElemQT = VecT->getElementType();
1511     PrimType ElemT = classifyPrim(ElemQT);
1512 
1513     for (unsigned I = 0; I < NumVecElements; ++I) {
1514       if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1515         return false;
1516       if (!this->emitInitElem(ElemT, I, E))
1517         return false;
1518     }
1519     return true;
1520   }
1521 
1522   return false;
1523 }
1524 
1525 template <class Emitter>
1526 bool Compiler<Emitter>::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
1527   const Expr *LHS = E->getLHS();
1528   const Expr *RHS = E->getRHS();
1529   const Expr *Index = E->getIdx();
1530 
1531   if (DiscardResult)
1532     return this->discard(LHS) && this->discard(RHS);
1533 
1534   // C++17's rules require us to evaluate the LHS first, regardless of which
1535   // side is the base.
1536   bool Success = true;
1537   for (const Expr *SubExpr : {LHS, RHS}) {
1538     if (!this->visit(SubExpr))
1539       Success = false;
1540   }
1541 
1542   if (!Success)
1543     return false;
1544 
1545   PrimType IndexT = classifyPrim(Index->getType());
1546   // If the index is first, we need to change that.
1547   if (LHS == Index) {
1548     if (!this->emitFlip(PT_Ptr, IndexT, E))
1549       return false;
1550   }
1551 
1552   return this->emitArrayElemPtrPop(IndexT, E);
1553 }
1554 
1555 template <class Emitter>
1556 bool Compiler<Emitter>::visitInitList(ArrayRef<const Expr *> Inits,
1557                                       const Expr *ArrayFiller, const Expr *E) {
1558   QualType QT = E->getType();
1559   if (const auto *AT = QT->getAs<AtomicType>())
1560     QT = AT->getValueType();
1561 
1562   if (QT->isVoidType()) {
1563     if (Inits.size() == 0)
1564       return true;
1565     return this->emitInvalid(E);
1566   }
1567 
1568   // Handle discarding first.
1569   if (DiscardResult) {
1570     for (const Expr *Init : Inits) {
1571       if (!this->discard(Init))
1572         return false;
1573     }
1574     return true;
1575   }
1576 
1577   // Primitive values.
1578   if (std::optional<PrimType> T = classify(QT)) {
1579     assert(!DiscardResult);
1580     if (Inits.size() == 0)
1581       return this->visitZeroInitializer(*T, QT, E);
1582     assert(Inits.size() == 1);
1583     return this->delegate(Inits[0]);
1584   }
1585 
1586   if (QT->isRecordType()) {
1587     const Record *R = getRecord(QT);
1588 
1589     if (Inits.size() == 1 && E->getType() == Inits[0]->getType())
1590       return this->delegate(Inits[0]);
1591 
1592     auto initPrimitiveField = [=](const Record::Field *FieldToInit,
1593                                   const Expr *Init, PrimType T) -> bool {
1594       InitStackScope<Emitter> ISS(this, isa<CXXDefaultInitExpr>(Init));
1595       if (!this->visit(Init))
1596         return false;
1597 
1598       if (FieldToInit->isBitField())
1599         return this->emitInitBitField(T, FieldToInit, E);
1600       return this->emitInitField(T, FieldToInit->Offset, E);
1601     };
1602 
1603     auto initCompositeField = [=](const Record::Field *FieldToInit,
1604                                   const Expr *Init) -> bool {
1605       InitStackScope<Emitter> ISS(this, isa<CXXDefaultInitExpr>(Init));
1606       InitLinkScope<Emitter> ILS(this, InitLink::Field(FieldToInit->Offset));
1607       // Non-primitive case. Get a pointer to the field-to-initialize
1608       // on the stack and recurse into visitInitializer().
1609       if (!this->emitGetPtrField(FieldToInit->Offset, Init))
1610         return false;
1611       if (!this->visitInitializer(Init))
1612         return false;
1613       return this->emitPopPtr(E);
1614     };
1615 
1616     if (R->isUnion()) {
1617       if (Inits.size() == 0) {
1618         if (!this->visitZeroRecordInitializer(R, E))
1619           return false;
1620       } else {
1621         const Expr *Init = Inits[0];
1622         const FieldDecl *FToInit = nullptr;
1623         if (const auto *ILE = dyn_cast<InitListExpr>(E))
1624           FToInit = ILE->getInitializedFieldInUnion();
1625         else
1626           FToInit = cast<CXXParenListInitExpr>(E)->getInitializedFieldInUnion();
1627 
1628         const Record::Field *FieldToInit = R->getField(FToInit);
1629         if (std::optional<PrimType> T = classify(Init)) {
1630           if (!initPrimitiveField(FieldToInit, Init, *T))
1631             return false;
1632         } else {
1633           if (!initCompositeField(FieldToInit, Init))
1634             return false;
1635         }
1636       }
1637       return this->emitFinishInit(E);
1638     }
1639 
1640     assert(!R->isUnion());
1641     unsigned InitIndex = 0;
1642     for (const Expr *Init : Inits) {
1643       // Skip unnamed bitfields.
1644       while (InitIndex < R->getNumFields() &&
1645              R->getField(InitIndex)->Decl->isUnnamedBitField())
1646         ++InitIndex;
1647 
1648       if (std::optional<PrimType> T = classify(Init)) {
1649         const Record::Field *FieldToInit = R->getField(InitIndex);
1650         if (!initPrimitiveField(FieldToInit, Init, *T))
1651           return false;
1652         ++InitIndex;
1653       } else {
1654         // Initializer for a direct base class.
1655         if (const Record::Base *B = R->getBase(Init->getType())) {
1656           if (!this->emitGetPtrBase(B->Offset, Init))
1657             return false;
1658 
1659           if (!this->visitInitializer(Init))
1660             return false;
1661 
1662           if (!this->emitFinishInitPop(E))
1663             return false;
1664           // Base initializers don't increase InitIndex, since they don't count
1665           // into the Record's fields.
1666         } else {
1667           const Record::Field *FieldToInit = R->getField(InitIndex);
1668           if (!initCompositeField(FieldToInit, Init))
1669             return false;
1670           ++InitIndex;
1671         }
1672       }
1673     }
1674     return this->emitFinishInit(E);
1675   }
1676 
1677   if (QT->isArrayType()) {
1678     if (Inits.size() == 1 && QT == Inits[0]->getType())
1679       return this->delegate(Inits[0]);
1680 
1681     unsigned ElementIndex = 0;
1682     for (const Expr *Init : Inits) {
1683       if (const auto *EmbedS =
1684               dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
1685         PrimType TargetT = classifyPrim(Init->getType());
1686 
1687         auto Eval = [&](const Expr *Init, unsigned ElemIndex) {
1688           PrimType InitT = classifyPrim(Init->getType());
1689           if (!this->visit(Init))
1690             return false;
1691           if (InitT != TargetT) {
1692             if (!this->emitCast(InitT, TargetT, E))
1693               return false;
1694           }
1695           return this->emitInitElem(TargetT, ElemIndex, Init);
1696         };
1697         if (!EmbedS->doForEachDataElement(Eval, ElementIndex))
1698           return false;
1699       } else {
1700         if (!this->visitArrayElemInit(ElementIndex, Init))
1701           return false;
1702         ++ElementIndex;
1703       }
1704     }
1705 
1706     // Expand the filler expression.
1707     // FIXME: This should go away.
1708     if (ArrayFiller) {
1709       const ConstantArrayType *CAT =
1710           Ctx.getASTContext().getAsConstantArrayType(QT);
1711       uint64_t NumElems = CAT->getZExtSize();
1712 
1713       for (; ElementIndex != NumElems; ++ElementIndex) {
1714         if (!this->visitArrayElemInit(ElementIndex, ArrayFiller))
1715           return false;
1716       }
1717     }
1718 
1719     return this->emitFinishInit(E);
1720   }
1721 
1722   if (const auto *ComplexTy = QT->getAs<ComplexType>()) {
1723     unsigned NumInits = Inits.size();
1724 
1725     if (NumInits == 1)
1726       return this->delegate(Inits[0]);
1727 
1728     QualType ElemQT = ComplexTy->getElementType();
1729     PrimType ElemT = classifyPrim(ElemQT);
1730     if (NumInits == 0) {
1731       // Zero-initialize both elements.
1732       for (unsigned I = 0; I < 2; ++I) {
1733         if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1734           return false;
1735         if (!this->emitInitElem(ElemT, I, E))
1736           return false;
1737       }
1738     } else if (NumInits == 2) {
1739       unsigned InitIndex = 0;
1740       for (const Expr *Init : Inits) {
1741         if (!this->visit(Init))
1742           return false;
1743 
1744         if (!this->emitInitElem(ElemT, InitIndex, E))
1745           return false;
1746         ++InitIndex;
1747       }
1748     }
1749     return true;
1750   }
1751 
1752   if (const auto *VecT = QT->getAs<VectorType>()) {
1753     unsigned NumVecElements = VecT->getNumElements();
1754     assert(NumVecElements >= Inits.size());
1755 
1756     QualType ElemQT = VecT->getElementType();
1757     PrimType ElemT = classifyPrim(ElemQT);
1758 
1759     // All initializer elements.
1760     unsigned InitIndex = 0;
1761     for (const Expr *Init : Inits) {
1762       if (!this->visit(Init))
1763         return false;
1764 
1765       // If the initializer is of vector type itself, we have to deconstruct
1766       // that and initialize all the target fields from the initializer fields.
1767       if (const auto *InitVecT = Init->getType()->getAs<VectorType>()) {
1768         if (!this->emitCopyArray(ElemT, 0, InitIndex,
1769                                  InitVecT->getNumElements(), E))
1770           return false;
1771         InitIndex += InitVecT->getNumElements();
1772       } else {
1773         if (!this->emitInitElem(ElemT, InitIndex, E))
1774           return false;
1775         ++InitIndex;
1776       }
1777     }
1778 
1779     assert(InitIndex <= NumVecElements);
1780 
1781     // Fill the rest with zeroes.
1782     for (; InitIndex != NumVecElements; ++InitIndex) {
1783       if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1784         return false;
1785       if (!this->emitInitElem(ElemT, InitIndex, E))
1786         return false;
1787     }
1788     return true;
1789   }
1790 
1791   return false;
1792 }
1793 
1794 /// Pointer to the array(not the element!) must be on the stack when calling
1795 /// this.
1796 template <class Emitter>
1797 bool Compiler<Emitter>::visitArrayElemInit(unsigned ElemIndex,
1798                                            const Expr *Init) {
1799   if (std::optional<PrimType> T = classify(Init->getType())) {
1800     // Visit the primitive element like normal.
1801     if (!this->visit(Init))
1802       return false;
1803     return this->emitInitElem(*T, ElemIndex, Init);
1804   }
1805 
1806   InitLinkScope<Emitter> ILS(this, InitLink::Elem(ElemIndex));
1807   // Advance the pointer currently on the stack to the given
1808   // dimension.
1809   if (!this->emitConstUint32(ElemIndex, Init))
1810     return false;
1811   if (!this->emitArrayElemPtrUint32(Init))
1812     return false;
1813   if (!this->visitInitializer(Init))
1814     return false;
1815   return this->emitFinishInitPop(Init);
1816 }
1817 
1818 template <class Emitter>
1819 bool Compiler<Emitter>::VisitInitListExpr(const InitListExpr *E) {
1820   return this->visitInitList(E->inits(), E->getArrayFiller(), E);
1821 }
1822 
1823 template <class Emitter>
1824 bool Compiler<Emitter>::VisitCXXParenListInitExpr(
1825     const CXXParenListInitExpr *E) {
1826   return this->visitInitList(E->getInitExprs(), E->getArrayFiller(), E);
1827 }
1828 
1829 template <class Emitter>
1830 bool Compiler<Emitter>::VisitSubstNonTypeTemplateParmExpr(
1831     const SubstNonTypeTemplateParmExpr *E) {
1832   return this->delegate(E->getReplacement());
1833 }
1834 
1835 template <class Emitter>
1836 bool Compiler<Emitter>::VisitConstantExpr(const ConstantExpr *E) {
1837   std::optional<PrimType> T = classify(E->getType());
1838   if (T && E->hasAPValueResult()) {
1839     // Try to emit the APValue directly, without visiting the subexpr.
1840     // This will only fail if we can't emit the APValue, so won't emit any
1841     // diagnostics or any double values.
1842     if (DiscardResult)
1843       return true;
1844 
1845     if (this->visitAPValue(E->getAPValueResult(), *T, E))
1846       return true;
1847   }
1848   return this->delegate(E->getSubExpr());
1849 }
1850 
1851 template <class Emitter>
1852 bool Compiler<Emitter>::VisitEmbedExpr(const EmbedExpr *E) {
1853   auto It = E->begin();
1854   return this->visit(*It);
1855 }
1856 
1857 static CharUnits AlignOfType(QualType T, const ASTContext &ASTCtx,
1858                              UnaryExprOrTypeTrait Kind) {
1859   bool AlignOfReturnsPreferred =
1860       ASTCtx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
1861 
1862   // C++ [expr.alignof]p3:
1863   //     When alignof is applied to a reference type, the result is the
1864   //     alignment of the referenced type.
1865   if (const auto *Ref = T->getAs<ReferenceType>())
1866     T = Ref->getPointeeType();
1867 
1868   if (T.getQualifiers().hasUnaligned())
1869     return CharUnits::One();
1870 
1871   // __alignof is defined to return the preferred alignment.
1872   // Before 8, clang returned the preferred alignment for alignof and
1873   // _Alignof as well.
1874   if (Kind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
1875     return ASTCtx.toCharUnitsFromBits(ASTCtx.getPreferredTypeAlign(T));
1876 
1877   return ASTCtx.getTypeAlignInChars(T);
1878 }
1879 
1880 template <class Emitter>
1881 bool Compiler<Emitter>::VisitUnaryExprOrTypeTraitExpr(
1882     const UnaryExprOrTypeTraitExpr *E) {
1883   UnaryExprOrTypeTrait Kind = E->getKind();
1884   const ASTContext &ASTCtx = Ctx.getASTContext();
1885 
1886   if (Kind == UETT_SizeOf || Kind == UETT_DataSizeOf) {
1887     QualType ArgType = E->getTypeOfArgument();
1888 
1889     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1890     //   the result is the size of the referenced type."
1891     if (const auto *Ref = ArgType->getAs<ReferenceType>())
1892       ArgType = Ref->getPointeeType();
1893 
1894     CharUnits Size;
1895     if (ArgType->isVoidType() || ArgType->isFunctionType())
1896       Size = CharUnits::One();
1897     else {
1898       if (ArgType->isDependentType() || !ArgType->isConstantSizeType())
1899         return false;
1900 
1901       if (Kind == UETT_SizeOf)
1902         Size = ASTCtx.getTypeSizeInChars(ArgType);
1903       else
1904         Size = ASTCtx.getTypeInfoDataSizeInChars(ArgType).Width;
1905     }
1906 
1907     if (DiscardResult)
1908       return true;
1909 
1910     return this->emitConst(Size.getQuantity(), E);
1911   }
1912 
1913   if (Kind == UETT_AlignOf || Kind == UETT_PreferredAlignOf) {
1914     CharUnits Size;
1915 
1916     if (E->isArgumentType()) {
1917       QualType ArgType = E->getTypeOfArgument();
1918 
1919       Size = AlignOfType(ArgType, ASTCtx, Kind);
1920     } else {
1921       // Argument is an expression, not a type.
1922       const Expr *Arg = E->getArgumentExpr()->IgnoreParens();
1923 
1924       // The kinds of expressions that we have special-case logic here for
1925       // should be kept up to date with the special checks for those
1926       // expressions in Sema.
1927 
1928       // alignof decl is always accepted, even if it doesn't make sense: we
1929       // default to 1 in those cases.
1930       if (const auto *DRE = dyn_cast<DeclRefExpr>(Arg))
1931         Size = ASTCtx.getDeclAlign(DRE->getDecl(),
1932                                    /*RefAsPointee*/ true);
1933       else if (const auto *ME = dyn_cast<MemberExpr>(Arg))
1934         Size = ASTCtx.getDeclAlign(ME->getMemberDecl(),
1935                                    /*RefAsPointee*/ true);
1936       else
1937         Size = AlignOfType(Arg->getType(), ASTCtx, Kind);
1938     }
1939 
1940     if (DiscardResult)
1941       return true;
1942 
1943     return this->emitConst(Size.getQuantity(), E);
1944   }
1945 
1946   if (Kind == UETT_VectorElements) {
1947     if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>())
1948       return this->emitConst(VT->getNumElements(), E);
1949     assert(E->getTypeOfArgument()->isSizelessVectorType());
1950     return this->emitSizelessVectorElementSize(E);
1951   }
1952 
1953   if (Kind == UETT_VecStep) {
1954     if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>()) {
1955       unsigned N = VT->getNumElements();
1956 
1957       // The vec_step built-in functions that take a 3-component
1958       // vector return 4. (OpenCL 1.1 spec 6.11.12)
1959       if (N == 3)
1960         N = 4;
1961 
1962       return this->emitConst(N, E);
1963     }
1964     return this->emitConst(1, E);
1965   }
1966 
1967   return false;
1968 }
1969 
1970 template <class Emitter>
1971 bool Compiler<Emitter>::VisitMemberExpr(const MemberExpr *E) {
1972   // 'Base.Member'
1973   const Expr *Base = E->getBase();
1974   const ValueDecl *Member = E->getMemberDecl();
1975 
1976   if (DiscardResult)
1977     return this->discard(Base);
1978 
1979   // MemberExprs are almost always lvalues, in which case we don't need to
1980   // do the load. But sometimes they aren't.
1981   const auto maybeLoadValue = [&]() -> bool {
1982     if (E->isGLValue())
1983       return true;
1984     if (std::optional<PrimType> T = classify(E))
1985       return this->emitLoadPop(*T, E);
1986     return false;
1987   };
1988 
1989   if (const auto *VD = dyn_cast<VarDecl>(Member)) {
1990     // I am almost confident in saying that a var decl must be static
1991     // and therefore registered as a global variable. But this will probably
1992     // turn out to be wrong some time in the future, as always.
1993     if (auto GlobalIndex = P.getGlobal(VD))
1994       return this->emitGetPtrGlobal(*GlobalIndex, E) && maybeLoadValue();
1995     return false;
1996   }
1997 
1998   if (!isa<FieldDecl>(Member)) {
1999     if (!this->discard(Base) && !this->emitSideEffect(E))
2000       return false;
2001 
2002     return this->visitDeclRef(Member, E);
2003   }
2004 
2005   if (Initializing) {
2006     if (!this->delegate(Base))
2007       return false;
2008   } else {
2009     if (!this->visit(Base))
2010       return false;
2011   }
2012 
2013   // Base above gives us a pointer on the stack.
2014   const auto *FD = cast<FieldDecl>(Member);
2015   const RecordDecl *RD = FD->getParent();
2016   const Record *R = getRecord(RD);
2017   if (!R)
2018     return false;
2019   const Record::Field *F = R->getField(FD);
2020   // Leave a pointer to the field on the stack.
2021   if (F->Decl->getType()->isReferenceType())
2022     return this->emitGetFieldPop(PT_Ptr, F->Offset, E) && maybeLoadValue();
2023   return this->emitGetPtrFieldPop(F->Offset, E) && maybeLoadValue();
2024 }
2025 
2026 template <class Emitter>
2027 bool Compiler<Emitter>::VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
2028   // ArrayIndex might not be set if a ArrayInitIndexExpr is being evaluated
2029   // stand-alone, e.g. via EvaluateAsInt().
2030   if (!ArrayIndex)
2031     return false;
2032   return this->emitConst(*ArrayIndex, E);
2033 }
2034 
2035 template <class Emitter>
2036 bool Compiler<Emitter>::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
2037   assert(Initializing);
2038   assert(!DiscardResult);
2039 
2040   // We visit the common opaque expression here once so we have its value
2041   // cached.
2042   if (!this->discard(E->getCommonExpr()))
2043     return false;
2044 
2045   // TODO: This compiles to quite a lot of bytecode if the array is larger.
2046   //   Investigate compiling this to a loop.
2047   const Expr *SubExpr = E->getSubExpr();
2048   size_t Size = E->getArraySize().getZExtValue();
2049 
2050   // So, every iteration, we execute an assignment here
2051   // where the LHS is on the stack (the target array)
2052   // and the RHS is our SubExpr.
2053   for (size_t I = 0; I != Size; ++I) {
2054     ArrayIndexScope<Emitter> IndexScope(this, I);
2055     BlockScope<Emitter> BS(this);
2056 
2057     if (!this->visitArrayElemInit(I, SubExpr))
2058       return false;
2059     if (!BS.destroyLocals())
2060       return false;
2061   }
2062   return true;
2063 }
2064 
2065 template <class Emitter>
2066 bool Compiler<Emitter>::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2067   const Expr *SourceExpr = E->getSourceExpr();
2068   if (!SourceExpr)
2069     return false;
2070 
2071   if (Initializing)
2072     return this->visitInitializer(SourceExpr);
2073 
2074   PrimType SubExprT = classify(SourceExpr).value_or(PT_Ptr);
2075   if (auto It = OpaqueExprs.find(E); It != OpaqueExprs.end())
2076     return this->emitGetLocal(SubExprT, It->second, E);
2077 
2078   if (!this->visit(SourceExpr))
2079     return false;
2080 
2081   // At this point we either have the evaluated source expression or a pointer
2082   // to an object on the stack. We want to create a local variable that stores
2083   // this value.
2084   unsigned LocalIndex = allocateLocalPrimitive(E, SubExprT, /*IsConst=*/true);
2085   if (!this->emitSetLocal(SubExprT, LocalIndex, E))
2086     return false;
2087 
2088   // Here the local variable is created but the value is removed from the stack,
2089   // so we put it back if the caller needs it.
2090   if (!DiscardResult) {
2091     if (!this->emitGetLocal(SubExprT, LocalIndex, E))
2092       return false;
2093   }
2094 
2095   // This is cleaned up when the local variable is destroyed.
2096   OpaqueExprs.insert({E, LocalIndex});
2097 
2098   return true;
2099 }
2100 
2101 template <class Emitter>
2102 bool Compiler<Emitter>::VisitAbstractConditionalOperator(
2103     const AbstractConditionalOperator *E) {
2104   const Expr *Condition = E->getCond();
2105   const Expr *TrueExpr = E->getTrueExpr();
2106   const Expr *FalseExpr = E->getFalseExpr();
2107 
2108   LabelTy LabelEnd = this->getLabel();   // Label after the operator.
2109   LabelTy LabelFalse = this->getLabel(); // Label for the false expr.
2110 
2111   if (!this->visitBool(Condition))
2112     return false;
2113 
2114   if (!this->jumpFalse(LabelFalse))
2115     return false;
2116 
2117   {
2118     LocalScope<Emitter> S(this);
2119     if (!this->delegate(TrueExpr))
2120       return false;
2121     if (!S.destroyLocals())
2122       return false;
2123   }
2124 
2125   if (!this->jump(LabelEnd))
2126     return false;
2127 
2128   this->emitLabel(LabelFalse);
2129 
2130   {
2131     LocalScope<Emitter> S(this);
2132     if (!this->delegate(FalseExpr))
2133       return false;
2134     if (!S.destroyLocals())
2135       return false;
2136   }
2137 
2138   this->fallthrough(LabelEnd);
2139   this->emitLabel(LabelEnd);
2140 
2141   return true;
2142 }
2143 
2144 template <class Emitter>
2145 bool Compiler<Emitter>::VisitStringLiteral(const StringLiteral *E) {
2146   if (DiscardResult)
2147     return true;
2148 
2149   if (!Initializing) {
2150     unsigned StringIndex = P.createGlobalString(E);
2151     return this->emitGetPtrGlobal(StringIndex, E);
2152   }
2153 
2154   // We are initializing an array on the stack.
2155   const ConstantArrayType *CAT =
2156       Ctx.getASTContext().getAsConstantArrayType(E->getType());
2157   assert(CAT && "a string literal that's not a constant array?");
2158 
2159   // If the initializer string is too long, a diagnostic has already been
2160   // emitted. Read only the array length from the string literal.
2161   unsigned ArraySize = CAT->getZExtSize();
2162   unsigned N = std::min(ArraySize, E->getLength());
2163   size_t CharWidth = E->getCharByteWidth();
2164 
2165   for (unsigned I = 0; I != N; ++I) {
2166     uint32_t CodeUnit = E->getCodeUnit(I);
2167 
2168     if (CharWidth == 1) {
2169       this->emitConstSint8(CodeUnit, E);
2170       this->emitInitElemSint8(I, E);
2171     } else if (CharWidth == 2) {
2172       this->emitConstUint16(CodeUnit, E);
2173       this->emitInitElemUint16(I, E);
2174     } else if (CharWidth == 4) {
2175       this->emitConstUint32(CodeUnit, E);
2176       this->emitInitElemUint32(I, E);
2177     } else {
2178       llvm_unreachable("unsupported character width");
2179     }
2180   }
2181 
2182   // Fill up the rest of the char array with NUL bytes.
2183   for (unsigned I = N; I != ArraySize; ++I) {
2184     if (CharWidth == 1) {
2185       this->emitConstSint8(0, E);
2186       this->emitInitElemSint8(I, E);
2187     } else if (CharWidth == 2) {
2188       this->emitConstUint16(0, E);
2189       this->emitInitElemUint16(I, E);
2190     } else if (CharWidth == 4) {
2191       this->emitConstUint32(0, E);
2192       this->emitInitElemUint32(I, E);
2193     } else {
2194       llvm_unreachable("unsupported character width");
2195     }
2196   }
2197 
2198   return true;
2199 }
2200 
2201 template <class Emitter>
2202 bool Compiler<Emitter>::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
2203   if (std::optional<unsigned> I = P.getOrCreateDummy(E))
2204     return this->emitGetPtrGlobal(*I, E);
2205   return false;
2206 }
2207 
2208 template <class Emitter>
2209 bool Compiler<Emitter>::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
2210   auto &A = Ctx.getASTContext();
2211   std::string Str;
2212   A.getObjCEncodingForType(E->getEncodedType(), Str);
2213   StringLiteral *SL =
2214       StringLiteral::Create(A, Str, StringLiteralKind::Ordinary,
2215                             /*Pascal=*/false, E->getType(), E->getAtLoc());
2216   return this->delegate(SL);
2217 }
2218 
2219 template <class Emitter>
2220 bool Compiler<Emitter>::VisitSYCLUniqueStableNameExpr(
2221     const SYCLUniqueStableNameExpr *E) {
2222   if (DiscardResult)
2223     return true;
2224 
2225   assert(!Initializing);
2226 
2227   auto &A = Ctx.getASTContext();
2228   std::string ResultStr = E->ComputeName(A);
2229 
2230   QualType CharTy = A.CharTy.withConst();
2231   APInt Size(A.getTypeSize(A.getSizeType()), ResultStr.size() + 1);
2232   QualType ArrayTy = A.getConstantArrayType(CharTy, Size, nullptr,
2233                                             ArraySizeModifier::Normal, 0);
2234 
2235   StringLiteral *SL =
2236       StringLiteral::Create(A, ResultStr, StringLiteralKind::Ordinary,
2237                             /*Pascal=*/false, ArrayTy, E->getLocation());
2238 
2239   unsigned StringIndex = P.createGlobalString(SL);
2240   return this->emitGetPtrGlobal(StringIndex, E);
2241 }
2242 
2243 template <class Emitter>
2244 bool Compiler<Emitter>::VisitCharacterLiteral(const CharacterLiteral *E) {
2245   if (DiscardResult)
2246     return true;
2247   return this->emitConst(E->getValue(), E);
2248 }
2249 
2250 template <class Emitter>
2251 bool Compiler<Emitter>::VisitFloatCompoundAssignOperator(
2252     const CompoundAssignOperator *E) {
2253 
2254   const Expr *LHS = E->getLHS();
2255   const Expr *RHS = E->getRHS();
2256   QualType LHSType = LHS->getType();
2257   QualType LHSComputationType = E->getComputationLHSType();
2258   QualType ResultType = E->getComputationResultType();
2259   std::optional<PrimType> LT = classify(LHSComputationType);
2260   std::optional<PrimType> RT = classify(ResultType);
2261 
2262   assert(ResultType->isFloatingType());
2263 
2264   if (!LT || !RT)
2265     return false;
2266 
2267   PrimType LHST = classifyPrim(LHSType);
2268 
2269   // C++17 onwards require that we evaluate the RHS first.
2270   // Compute RHS and save it in a temporary variable so we can
2271   // load it again later.
2272   if (!visit(RHS))
2273     return false;
2274 
2275   unsigned TempOffset = this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true);
2276   if (!this->emitSetLocal(*RT, TempOffset, E))
2277     return false;
2278 
2279   // First, visit LHS.
2280   if (!visit(LHS))
2281     return false;
2282   if (!this->emitLoad(LHST, E))
2283     return false;
2284 
2285   // If necessary, convert LHS to its computation type.
2286   if (!this->emitPrimCast(LHST, classifyPrim(LHSComputationType),
2287                           LHSComputationType, E))
2288     return false;
2289 
2290   // Now load RHS.
2291   if (!this->emitGetLocal(*RT, TempOffset, E))
2292     return false;
2293 
2294   switch (E->getOpcode()) {
2295   case BO_AddAssign:
2296     if (!this->emitAddf(getFPOptions(E), E))
2297       return false;
2298     break;
2299   case BO_SubAssign:
2300     if (!this->emitSubf(getFPOptions(E), E))
2301       return false;
2302     break;
2303   case BO_MulAssign:
2304     if (!this->emitMulf(getFPOptions(E), E))
2305       return false;
2306     break;
2307   case BO_DivAssign:
2308     if (!this->emitDivf(getFPOptions(E), E))
2309       return false;
2310     break;
2311   default:
2312     return false;
2313   }
2314 
2315   if (!this->emitPrimCast(classifyPrim(ResultType), LHST, LHS->getType(), E))
2316     return false;
2317 
2318   if (DiscardResult)
2319     return this->emitStorePop(LHST, E);
2320   return this->emitStore(LHST, E);
2321 }
2322 
2323 template <class Emitter>
2324 bool Compiler<Emitter>::VisitPointerCompoundAssignOperator(
2325     const CompoundAssignOperator *E) {
2326   BinaryOperatorKind Op = E->getOpcode();
2327   const Expr *LHS = E->getLHS();
2328   const Expr *RHS = E->getRHS();
2329   std::optional<PrimType> LT = classify(LHS->getType());
2330   std::optional<PrimType> RT = classify(RHS->getType());
2331 
2332   if (Op != BO_AddAssign && Op != BO_SubAssign)
2333     return false;
2334 
2335   if (!LT || !RT)
2336     return false;
2337 
2338   if (!visit(LHS))
2339     return false;
2340 
2341   if (!this->emitLoad(*LT, LHS))
2342     return false;
2343 
2344   if (!visit(RHS))
2345     return false;
2346 
2347   if (Op == BO_AddAssign) {
2348     if (!this->emitAddOffset(*RT, E))
2349       return false;
2350   } else {
2351     if (!this->emitSubOffset(*RT, E))
2352       return false;
2353   }
2354 
2355   if (DiscardResult)
2356     return this->emitStorePopPtr(E);
2357   return this->emitStorePtr(E);
2358 }
2359 
2360 template <class Emitter>
2361 bool Compiler<Emitter>::VisitCompoundAssignOperator(
2362     const CompoundAssignOperator *E) {
2363   if (E->getType()->isVectorType())
2364     return VisitVectorBinOp(E);
2365 
2366   const Expr *LHS = E->getLHS();
2367   const Expr *RHS = E->getRHS();
2368   std::optional<PrimType> LHSComputationT =
2369       classify(E->getComputationLHSType());
2370   std::optional<PrimType> LT = classify(LHS->getType());
2371   std::optional<PrimType> RT = classify(RHS->getType());
2372   std::optional<PrimType> ResultT = classify(E->getType());
2373 
2374   if (!Ctx.getLangOpts().CPlusPlus14)
2375     return this->visit(RHS) && this->visit(LHS) && this->emitError(E);
2376 
2377   if (!LT || !RT || !ResultT || !LHSComputationT)
2378     return false;
2379 
2380   // Handle floating point operations separately here, since they
2381   // require special care.
2382 
2383   if (ResultT == PT_Float || RT == PT_Float)
2384     return VisitFloatCompoundAssignOperator(E);
2385 
2386   if (E->getType()->isPointerType())
2387     return VisitPointerCompoundAssignOperator(E);
2388 
2389   assert(!E->getType()->isPointerType() && "Handled above");
2390   assert(!E->getType()->isFloatingType() && "Handled above");
2391 
2392   // C++17 onwards require that we evaluate the RHS first.
2393   // Compute RHS and save it in a temporary variable so we can
2394   // load it again later.
2395   // FIXME: Compound assignments are unsequenced in C, so we might
2396   //   have to figure out how to reject them.
2397   if (!visit(RHS))
2398     return false;
2399 
2400   unsigned TempOffset = this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true);
2401 
2402   if (!this->emitSetLocal(*RT, TempOffset, E))
2403     return false;
2404 
2405   // Get LHS pointer, load its value and cast it to the
2406   // computation type if necessary.
2407   if (!visit(LHS))
2408     return false;
2409   if (!this->emitLoad(*LT, E))
2410     return false;
2411   if (LT != LHSComputationT) {
2412     if (!this->emitCast(*LT, *LHSComputationT, E))
2413       return false;
2414   }
2415 
2416   // Get the RHS value on the stack.
2417   if (!this->emitGetLocal(*RT, TempOffset, E))
2418     return false;
2419 
2420   // Perform operation.
2421   switch (E->getOpcode()) {
2422   case BO_AddAssign:
2423     if (!this->emitAdd(*LHSComputationT, E))
2424       return false;
2425     break;
2426   case BO_SubAssign:
2427     if (!this->emitSub(*LHSComputationT, E))
2428       return false;
2429     break;
2430   case BO_MulAssign:
2431     if (!this->emitMul(*LHSComputationT, E))
2432       return false;
2433     break;
2434   case BO_DivAssign:
2435     if (!this->emitDiv(*LHSComputationT, E))
2436       return false;
2437     break;
2438   case BO_RemAssign:
2439     if (!this->emitRem(*LHSComputationT, E))
2440       return false;
2441     break;
2442   case BO_ShlAssign:
2443     if (!this->emitShl(*LHSComputationT, *RT, E))
2444       return false;
2445     break;
2446   case BO_ShrAssign:
2447     if (!this->emitShr(*LHSComputationT, *RT, E))
2448       return false;
2449     break;
2450   case BO_AndAssign:
2451     if (!this->emitBitAnd(*LHSComputationT, E))
2452       return false;
2453     break;
2454   case BO_XorAssign:
2455     if (!this->emitBitXor(*LHSComputationT, E))
2456       return false;
2457     break;
2458   case BO_OrAssign:
2459     if (!this->emitBitOr(*LHSComputationT, E))
2460       return false;
2461     break;
2462   default:
2463     llvm_unreachable("Unimplemented compound assign operator");
2464   }
2465 
2466   // And now cast from LHSComputationT to ResultT.
2467   if (ResultT != LHSComputationT) {
2468     if (!this->emitCast(*LHSComputationT, *ResultT, E))
2469       return false;
2470   }
2471 
2472   // And store the result in LHS.
2473   if (DiscardResult) {
2474     if (LHS->refersToBitField())
2475       return this->emitStoreBitFieldPop(*ResultT, E);
2476     return this->emitStorePop(*ResultT, E);
2477   }
2478   if (LHS->refersToBitField())
2479     return this->emitStoreBitField(*ResultT, E);
2480   return this->emitStore(*ResultT, E);
2481 }
2482 
2483 template <class Emitter>
2484 bool Compiler<Emitter>::VisitExprWithCleanups(const ExprWithCleanups *E) {
2485   LocalScope<Emitter> ES(this);
2486   const Expr *SubExpr = E->getSubExpr();
2487 
2488   return this->delegate(SubExpr) && ES.destroyLocals(E);
2489 }
2490 
2491 template <class Emitter>
2492 bool Compiler<Emitter>::VisitMaterializeTemporaryExpr(
2493     const MaterializeTemporaryExpr *E) {
2494   const Expr *SubExpr = E->getSubExpr();
2495 
2496   if (Initializing) {
2497     // We already have a value, just initialize that.
2498     return this->delegate(SubExpr);
2499   }
2500   // If we don't end up using the materialized temporary anyway, don't
2501   // bother creating it.
2502   if (DiscardResult)
2503     return this->discard(SubExpr);
2504 
2505   // When we're initializing a global variable *or* the storage duration of
2506   // the temporary is explicitly static, create a global variable.
2507   std::optional<PrimType> SubExprT = classify(SubExpr);
2508   bool IsStatic = E->getStorageDuration() == SD_Static;
2509   if (IsStatic) {
2510     std::optional<unsigned> GlobalIndex = P.createGlobal(E);
2511     if (!GlobalIndex)
2512       return false;
2513 
2514     const LifetimeExtendedTemporaryDecl *TempDecl =
2515         E->getLifetimeExtendedTemporaryDecl();
2516     if (IsStatic)
2517       assert(TempDecl);
2518 
2519     if (SubExprT) {
2520       if (!this->visit(SubExpr))
2521         return false;
2522       if (IsStatic) {
2523         if (!this->emitInitGlobalTemp(*SubExprT, *GlobalIndex, TempDecl, E))
2524           return false;
2525       } else {
2526         if (!this->emitInitGlobal(*SubExprT, *GlobalIndex, E))
2527           return false;
2528       }
2529       return this->emitGetPtrGlobal(*GlobalIndex, E);
2530     }
2531 
2532     if (!this->checkLiteralType(SubExpr))
2533       return false;
2534     // Non-primitive values.
2535     if (!this->emitGetPtrGlobal(*GlobalIndex, E))
2536       return false;
2537     if (!this->visitInitializer(SubExpr))
2538       return false;
2539     if (IsStatic)
2540       return this->emitInitGlobalTempComp(TempDecl, E);
2541     return true;
2542   }
2543 
2544   // For everyhing else, use local variables.
2545   if (SubExprT) {
2546     unsigned LocalIndex = allocateLocalPrimitive(E, *SubExprT, /*IsConst=*/true,
2547                                                  /*IsExtended=*/true);
2548     if (!this->visit(SubExpr))
2549       return false;
2550     if (!this->emitSetLocal(*SubExprT, LocalIndex, E))
2551       return false;
2552     return this->emitGetPtrLocal(LocalIndex, E);
2553   } else {
2554 
2555     if (!this->checkLiteralType(SubExpr))
2556       return false;
2557 
2558     const Expr *Inner = E->getSubExpr()->skipRValueSubobjectAdjustments();
2559     if (std::optional<unsigned> LocalIndex =
2560             allocateLocal(Inner, E->getExtendingDecl())) {
2561       InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
2562       if (!this->emitGetPtrLocal(*LocalIndex, E))
2563         return false;
2564       return this->visitInitializer(SubExpr);
2565     }
2566   }
2567   return false;
2568 }
2569 
2570 template <class Emitter>
2571 bool Compiler<Emitter>::VisitCXXBindTemporaryExpr(
2572     const CXXBindTemporaryExpr *E) {
2573   return this->delegate(E->getSubExpr());
2574 }
2575 
2576 template <class Emitter>
2577 bool Compiler<Emitter>::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2578   const Expr *Init = E->getInitializer();
2579   if (DiscardResult)
2580     return this->discard(Init);
2581 
2582   if (Initializing) {
2583     // We already have a value, just initialize that.
2584     return this->visitInitializer(Init) && this->emitFinishInit(E);
2585   }
2586 
2587   std::optional<PrimType> T = classify(E->getType());
2588   if (E->isFileScope()) {
2589     // Avoid creating a variable if this is a primitive RValue anyway.
2590     if (T && !E->isLValue())
2591       return this->delegate(Init);
2592 
2593     if (std::optional<unsigned> GlobalIndex = P.createGlobal(E)) {
2594       if (!this->emitGetPtrGlobal(*GlobalIndex, E))
2595         return false;
2596 
2597       if (T) {
2598         if (!this->visit(Init))
2599           return false;
2600         return this->emitInitGlobal(*T, *GlobalIndex, E);
2601       }
2602 
2603       return this->visitInitializer(Init) && this->emitFinishInit(E);
2604     }
2605 
2606     return false;
2607   }
2608 
2609   // Otherwise, use a local variable.
2610   if (T && !E->isLValue()) {
2611     // For primitive types, we just visit the initializer.
2612     return this->delegate(Init);
2613   } else {
2614     unsigned LocalIndex;
2615 
2616     if (T)
2617       LocalIndex = this->allocateLocalPrimitive(Init, *T, false, false);
2618     else if (std::optional<unsigned> MaybeIndex = this->allocateLocal(Init))
2619       LocalIndex = *MaybeIndex;
2620     else
2621       return false;
2622 
2623     if (!this->emitGetPtrLocal(LocalIndex, E))
2624       return false;
2625 
2626     if (T) {
2627       if (!this->visit(Init)) {
2628         return false;
2629       }
2630       return this->emitInit(*T, E);
2631     } else {
2632       if (!this->visitInitializer(Init) || !this->emitFinishInit(E))
2633         return false;
2634     }
2635     return true;
2636   }
2637 
2638   return false;
2639 }
2640 
2641 template <class Emitter>
2642 bool Compiler<Emitter>::VisitTypeTraitExpr(const TypeTraitExpr *E) {
2643   if (DiscardResult)
2644     return true;
2645   if (E->getType()->isBooleanType())
2646     return this->emitConstBool(E->getValue(), E);
2647   return this->emitConst(E->getValue(), E);
2648 }
2649 
2650 template <class Emitter>
2651 bool Compiler<Emitter>::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2652   if (DiscardResult)
2653     return true;
2654   return this->emitConst(E->getValue(), E);
2655 }
2656 
2657 template <class Emitter>
2658 bool Compiler<Emitter>::VisitLambdaExpr(const LambdaExpr *E) {
2659   if (DiscardResult)
2660     return true;
2661 
2662   assert(Initializing);
2663   const Record *R = P.getOrCreateRecord(E->getLambdaClass());
2664 
2665   auto *CaptureInitIt = E->capture_init_begin();
2666   // Initialize all fields (which represent lambda captures) of the
2667   // record with their initializers.
2668   for (const Record::Field &F : R->fields()) {
2669     const Expr *Init = *CaptureInitIt;
2670     ++CaptureInitIt;
2671 
2672     if (!Init)
2673       continue;
2674 
2675     if (std::optional<PrimType> T = classify(Init)) {
2676       if (!this->visit(Init))
2677         return false;
2678 
2679       if (!this->emitInitField(*T, F.Offset, E))
2680         return false;
2681     } else {
2682       if (!this->emitGetPtrField(F.Offset, E))
2683         return false;
2684 
2685       if (!this->visitInitializer(Init))
2686         return false;
2687 
2688       if (!this->emitPopPtr(E))
2689         return false;
2690     }
2691   }
2692 
2693   return true;
2694 }
2695 
2696 template <class Emitter>
2697 bool Compiler<Emitter>::VisitPredefinedExpr(const PredefinedExpr *E) {
2698   if (DiscardResult)
2699     return true;
2700 
2701   return this->delegate(E->getFunctionName());
2702 }
2703 
2704 template <class Emitter>
2705 bool Compiler<Emitter>::VisitCXXThrowExpr(const CXXThrowExpr *E) {
2706   if (E->getSubExpr() && !this->discard(E->getSubExpr()))
2707     return false;
2708 
2709   return this->emitInvalid(E);
2710 }
2711 
2712 template <class Emitter>
2713 bool Compiler<Emitter>::VisitCXXReinterpretCastExpr(
2714     const CXXReinterpretCastExpr *E) {
2715   const Expr *SubExpr = E->getSubExpr();
2716 
2717   std::optional<PrimType> FromT = classify(SubExpr);
2718   std::optional<PrimType> ToT = classify(E);
2719 
2720   if (!FromT || !ToT)
2721     return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, E);
2722 
2723   if (FromT == PT_Ptr || ToT == PT_Ptr) {
2724     // Both types could be PT_Ptr because their expressions are glvalues.
2725     std::optional<PrimType> PointeeFromT;
2726     if (SubExpr->getType()->isPointerOrReferenceType())
2727       PointeeFromT = classify(SubExpr->getType()->getPointeeType());
2728     else
2729       PointeeFromT = classify(SubExpr->getType());
2730 
2731     std::optional<PrimType> PointeeToT;
2732     if (E->getType()->isPointerOrReferenceType())
2733       PointeeToT = classify(E->getType()->getPointeeType());
2734     else
2735       PointeeToT = classify(E->getType());
2736 
2737     bool Fatal = true;
2738     if (PointeeToT && PointeeFromT) {
2739       if (isIntegralType(*PointeeFromT) && isIntegralType(*PointeeToT))
2740         Fatal = false;
2741     }
2742 
2743     if (!this->emitInvalidCast(CastKind::Reinterpret, Fatal, E))
2744       return false;
2745 
2746     if (E->getCastKind() == CK_LValueBitCast)
2747       return this->delegate(SubExpr);
2748     return this->VisitCastExpr(E);
2749   }
2750 
2751   // Try to actually do the cast.
2752   bool Fatal = (ToT != FromT);
2753   if (!this->emitInvalidCast(CastKind::Reinterpret, Fatal, E))
2754     return false;
2755 
2756   return this->VisitCastExpr(E);
2757 }
2758 
2759 template <class Emitter>
2760 bool Compiler<Emitter>::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2761   assert(E->getType()->isBooleanType());
2762 
2763   if (DiscardResult)
2764     return true;
2765   return this->emitConstBool(E->getValue(), E);
2766 }
2767 
2768 template <class Emitter>
2769 bool Compiler<Emitter>::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2770   QualType T = E->getType();
2771   assert(!classify(T));
2772 
2773   if (T->isRecordType()) {
2774     const CXXConstructorDecl *Ctor = E->getConstructor();
2775 
2776     // Trivial copy/move constructor. Avoid copy.
2777     if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
2778         Ctor->isTrivial() &&
2779         E->getArg(0)->isTemporaryObject(Ctx.getASTContext(),
2780                                         T->getAsCXXRecordDecl()))
2781       return this->visitInitializer(E->getArg(0));
2782 
2783     // If we're discarding a construct expression, we still need
2784     // to allocate a variable and call the constructor and destructor.
2785     if (DiscardResult) {
2786       if (Ctor->isTrivial())
2787         return true;
2788       assert(!Initializing);
2789       std::optional<unsigned> LocalIndex = allocateLocal(E);
2790 
2791       if (!LocalIndex)
2792         return false;
2793 
2794       if (!this->emitGetPtrLocal(*LocalIndex, E))
2795         return false;
2796     }
2797 
2798     // Zero initialization.
2799     if (E->requiresZeroInitialization()) {
2800       const Record *R = getRecord(E->getType());
2801 
2802       if (!this->visitZeroRecordInitializer(R, E))
2803         return false;
2804 
2805       // If the constructor is trivial anyway, we're done.
2806       if (Ctor->isTrivial())
2807         return true;
2808     }
2809 
2810     const Function *Func = getFunction(Ctor);
2811 
2812     if (!Func)
2813       return false;
2814 
2815     assert(Func->hasThisPointer());
2816     assert(!Func->hasRVO());
2817 
2818     //  The This pointer is already on the stack because this is an initializer,
2819     //  but we need to dup() so the call() below has its own copy.
2820     if (!this->emitDupPtr(E))
2821       return false;
2822 
2823     // Constructor arguments.
2824     for (const auto *Arg : E->arguments()) {
2825       if (!this->visit(Arg))
2826         return false;
2827     }
2828 
2829     if (Func->isVariadic()) {
2830       uint32_t VarArgSize = 0;
2831       unsigned NumParams = Func->getNumWrittenParams();
2832       for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I) {
2833         VarArgSize +=
2834             align(primSize(classify(E->getArg(I)->getType()).value_or(PT_Ptr)));
2835       }
2836       if (!this->emitCallVar(Func, VarArgSize, E))
2837         return false;
2838     } else {
2839       if (!this->emitCall(Func, 0, E)) {
2840         // When discarding, we don't need the result anyway, so clean up
2841         // the instance dup we did earlier in case surrounding code wants
2842         // to keep evaluating.
2843         if (DiscardResult)
2844           (void)this->emitPopPtr(E);
2845         return false;
2846       }
2847     }
2848 
2849     if (DiscardResult)
2850       return this->emitPopPtr(E);
2851     return this->emitFinishInit(E);
2852   }
2853 
2854   if (T->isArrayType()) {
2855     const ConstantArrayType *CAT =
2856         Ctx.getASTContext().getAsConstantArrayType(E->getType());
2857     if (!CAT)
2858       return false;
2859 
2860     size_t NumElems = CAT->getZExtSize();
2861     const Function *Func = getFunction(E->getConstructor());
2862     if (!Func || !Func->isConstexpr())
2863       return false;
2864 
2865     // FIXME(perf): We're calling the constructor once per array element here,
2866     //   in the old intepreter we had a special-case for trivial constructors.
2867     for (size_t I = 0; I != NumElems; ++I) {
2868       if (!this->emitConstUint64(I, E))
2869         return false;
2870       if (!this->emitArrayElemPtrUint64(E))
2871         return false;
2872 
2873       // Constructor arguments.
2874       for (const auto *Arg : E->arguments()) {
2875         if (!this->visit(Arg))
2876           return false;
2877       }
2878 
2879       if (!this->emitCall(Func, 0, E))
2880         return false;
2881     }
2882     return true;
2883   }
2884 
2885   return false;
2886 }
2887 
2888 template <class Emitter>
2889 bool Compiler<Emitter>::VisitSourceLocExpr(const SourceLocExpr *E) {
2890   if (DiscardResult)
2891     return true;
2892 
2893   const APValue Val =
2894       E->EvaluateInContext(Ctx.getASTContext(), SourceLocDefaultExpr);
2895 
2896   // Things like __builtin_LINE().
2897   if (E->getType()->isIntegerType()) {
2898     assert(Val.isInt());
2899     const APSInt &I = Val.getInt();
2900     return this->emitConst(I, E);
2901   }
2902   // Otherwise, the APValue is an LValue, with only one element.
2903   // Theoretically, we don't need the APValue at all of course.
2904   assert(E->getType()->isPointerType());
2905   assert(Val.isLValue());
2906   const APValue::LValueBase &Base = Val.getLValueBase();
2907   if (const Expr *LValueExpr = Base.dyn_cast<const Expr *>())
2908     return this->visit(LValueExpr);
2909 
2910   // Otherwise, we have a decl (which is the case for
2911   // __builtin_source_location).
2912   assert(Base.is<const ValueDecl *>());
2913   assert(Val.getLValuePath().size() == 0);
2914   const auto *BaseDecl = Base.dyn_cast<const ValueDecl *>();
2915   assert(BaseDecl);
2916 
2917   auto *UGCD = cast<UnnamedGlobalConstantDecl>(BaseDecl);
2918 
2919   std::optional<unsigned> GlobalIndex = P.getOrCreateGlobal(UGCD);
2920   if (!GlobalIndex)
2921     return false;
2922 
2923   if (!this->emitGetPtrGlobal(*GlobalIndex, E))
2924     return false;
2925 
2926   const Record *R = getRecord(E->getType());
2927   const APValue &V = UGCD->getValue();
2928   for (unsigned I = 0, N = R->getNumFields(); I != N; ++I) {
2929     const Record::Field *F = R->getField(I);
2930     const APValue &FieldValue = V.getStructField(I);
2931 
2932     PrimType FieldT = classifyPrim(F->Decl->getType());
2933 
2934     if (!this->visitAPValue(FieldValue, FieldT, E))
2935       return false;
2936     if (!this->emitInitField(FieldT, F->Offset, E))
2937       return false;
2938   }
2939 
2940   // Leave the pointer to the global on the stack.
2941   return true;
2942 }
2943 
2944 template <class Emitter>
2945 bool Compiler<Emitter>::VisitOffsetOfExpr(const OffsetOfExpr *E) {
2946   unsigned N = E->getNumComponents();
2947   if (N == 0)
2948     return false;
2949 
2950   for (unsigned I = 0; I != N; ++I) {
2951     const OffsetOfNode &Node = E->getComponent(I);
2952     if (Node.getKind() == OffsetOfNode::Array) {
2953       const Expr *ArrayIndexExpr = E->getIndexExpr(Node.getArrayExprIndex());
2954       PrimType IndexT = classifyPrim(ArrayIndexExpr->getType());
2955 
2956       if (DiscardResult) {
2957         if (!this->discard(ArrayIndexExpr))
2958           return false;
2959         continue;
2960       }
2961 
2962       if (!this->visit(ArrayIndexExpr))
2963         return false;
2964       // Cast to Sint64.
2965       if (IndexT != PT_Sint64) {
2966         if (!this->emitCast(IndexT, PT_Sint64, E))
2967           return false;
2968       }
2969     }
2970   }
2971 
2972   if (DiscardResult)
2973     return true;
2974 
2975   PrimType T = classifyPrim(E->getType());
2976   return this->emitOffsetOf(T, E, E);
2977 }
2978 
2979 template <class Emitter>
2980 bool Compiler<Emitter>::VisitCXXScalarValueInitExpr(
2981     const CXXScalarValueInitExpr *E) {
2982   QualType Ty = E->getType();
2983 
2984   if (DiscardResult || Ty->isVoidType())
2985     return true;
2986 
2987   if (std::optional<PrimType> T = classify(Ty))
2988     return this->visitZeroInitializer(*T, Ty, E);
2989 
2990   if (const auto *CT = Ty->getAs<ComplexType>()) {
2991     if (!Initializing) {
2992       std::optional<unsigned> LocalIndex = allocateLocal(E);
2993       if (!LocalIndex)
2994         return false;
2995       if (!this->emitGetPtrLocal(*LocalIndex, E))
2996         return false;
2997     }
2998 
2999     // Initialize both fields to 0.
3000     QualType ElemQT = CT->getElementType();
3001     PrimType ElemT = classifyPrim(ElemQT);
3002 
3003     for (unsigned I = 0; I != 2; ++I) {
3004       if (!this->visitZeroInitializer(ElemT, ElemQT, E))
3005         return false;
3006       if (!this->emitInitElem(ElemT, I, E))
3007         return false;
3008     }
3009     return true;
3010   }
3011 
3012   if (const auto *VT = Ty->getAs<VectorType>()) {
3013     // FIXME: Code duplication with the _Complex case above.
3014     if (!Initializing) {
3015       std::optional<unsigned> LocalIndex = allocateLocal(E);
3016       if (!LocalIndex)
3017         return false;
3018       if (!this->emitGetPtrLocal(*LocalIndex, E))
3019         return false;
3020     }
3021 
3022     // Initialize all fields to 0.
3023     QualType ElemQT = VT->getElementType();
3024     PrimType ElemT = classifyPrim(ElemQT);
3025 
3026     for (unsigned I = 0, N = VT->getNumElements(); I != N; ++I) {
3027       if (!this->visitZeroInitializer(ElemT, ElemQT, E))
3028         return false;
3029       if (!this->emitInitElem(ElemT, I, E))
3030         return false;
3031     }
3032     return true;
3033   }
3034 
3035   return false;
3036 }
3037 
3038 template <class Emitter>
3039 bool Compiler<Emitter>::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
3040   return this->emitConst(E->getPackLength(), E);
3041 }
3042 
3043 template <class Emitter>
3044 bool Compiler<Emitter>::VisitGenericSelectionExpr(
3045     const GenericSelectionExpr *E) {
3046   return this->delegate(E->getResultExpr());
3047 }
3048 
3049 template <class Emitter>
3050 bool Compiler<Emitter>::VisitChooseExpr(const ChooseExpr *E) {
3051   return this->delegate(E->getChosenSubExpr());
3052 }
3053 
3054 template <class Emitter>
3055 bool Compiler<Emitter>::VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
3056   if (DiscardResult)
3057     return true;
3058 
3059   return this->emitConst(E->getValue(), E);
3060 }
3061 
3062 template <class Emitter>
3063 bool Compiler<Emitter>::VisitCXXInheritedCtorInitExpr(
3064     const CXXInheritedCtorInitExpr *E) {
3065   const CXXConstructorDecl *Ctor = E->getConstructor();
3066   assert(!Ctor->isTrivial() &&
3067          "Trivial CXXInheritedCtorInitExpr, implement. (possible?)");
3068   const Function *F = this->getFunction(Ctor);
3069   assert(F);
3070   assert(!F->hasRVO());
3071   assert(F->hasThisPointer());
3072 
3073   if (!this->emitDupPtr(SourceInfo{}))
3074     return false;
3075 
3076   // Forward all arguments of the current function (which should be a
3077   // constructor itself) to the inherited ctor.
3078   // This is necessary because the calling code has pushed the pointer
3079   // of the correct base for  us already, but the arguments need
3080   // to come after.
3081   unsigned Offset = align(primSize(PT_Ptr)); // instance pointer.
3082   for (const ParmVarDecl *PD : Ctor->parameters()) {
3083     PrimType PT = this->classify(PD->getType()).value_or(PT_Ptr);
3084 
3085     if (!this->emitGetParam(PT, Offset, E))
3086       return false;
3087     Offset += align(primSize(PT));
3088   }
3089 
3090   return this->emitCall(F, 0, E);
3091 }
3092 
3093 template <class Emitter>
3094 bool Compiler<Emitter>::VisitCXXNewExpr(const CXXNewExpr *E) {
3095   assert(classifyPrim(E->getType()) == PT_Ptr);
3096   const Expr *Init = E->getInitializer();
3097   QualType ElementType = E->getAllocatedType();
3098   std::optional<PrimType> ElemT = classify(ElementType);
3099   unsigned PlacementArgs = E->getNumPlacementArgs();
3100   const FunctionDecl *OperatorNew = E->getOperatorNew();
3101   const Expr *PlacementDest = nullptr;
3102   bool IsNoThrow = false;
3103 
3104   if (PlacementArgs != 0) {
3105     // FIXME: There is no restriction on this, but it's not clear that any
3106     // other form makes any sense. We get here for cases such as:
3107     //
3108     //   new (std::align_val_t{N}) X(int)
3109     //
3110     // (which should presumably be valid only if N is a multiple of
3111     // alignof(int), and in any case can't be deallocated unless N is
3112     // alignof(X) and X has new-extended alignment).
3113     if (PlacementArgs == 1) {
3114       const Expr *Arg1 = E->getPlacementArg(0);
3115       if (Arg1->getType()->isNothrowT()) {
3116         if (!this->discard(Arg1))
3117           return false;
3118         IsNoThrow = true;
3119       } else if (Ctx.getLangOpts().CPlusPlus26 &&
3120                  OperatorNew->isReservedGlobalPlacementOperator()) {
3121         // If we have a placement-new destination, we'll later use that instead
3122         // of allocating.
3123         PlacementDest = Arg1;
3124       } else {
3125         return this->emitInvalidNewDeleteExpr(E, E);
3126       }
3127 
3128     } else {
3129       return this->emitInvalid(E);
3130     }
3131   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
3132     return this->emitInvalidNewDeleteExpr(E, E);
3133   }
3134 
3135   const Descriptor *Desc;
3136   if (!PlacementDest) {
3137     if (ElemT) {
3138       if (E->isArray())
3139         Desc = nullptr; // We're not going to use it in this case.
3140       else
3141         Desc = P.createDescriptor(E, *ElemT, Descriptor::InlineDescMD,
3142                                   /*IsConst=*/false, /*IsTemporary=*/false,
3143                                   /*IsMutable=*/false);
3144     } else {
3145       Desc = P.createDescriptor(
3146           E, ElementType.getTypePtr(),
3147           E->isArray() ? std::nullopt : Descriptor::InlineDescMD,
3148           /*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false, Init);
3149     }
3150   }
3151 
3152   if (E->isArray()) {
3153     std::optional<const Expr *> ArraySizeExpr = E->getArraySize();
3154     if (!ArraySizeExpr)
3155       return false;
3156 
3157     const Expr *Stripped = *ArraySizeExpr;
3158     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
3159          Stripped = ICE->getSubExpr())
3160       if (ICE->getCastKind() != CK_NoOp &&
3161           ICE->getCastKind() != CK_IntegralCast)
3162         break;
3163 
3164     PrimType SizeT = classifyPrim(Stripped->getType());
3165 
3166     if (PlacementDest) {
3167       if (!this->visit(PlacementDest))
3168         return false;
3169       if (!this->visit(Stripped))
3170         return false;
3171       if (!this->emitCheckNewTypeMismatchArray(SizeT, E, E))
3172         return false;
3173     } else {
3174       if (!this->visit(Stripped))
3175         return false;
3176 
3177       if (ElemT) {
3178         // N primitive elements.
3179         if (!this->emitAllocN(SizeT, *ElemT, E, IsNoThrow, E))
3180           return false;
3181       } else {
3182         // N Composite elements.
3183         if (!this->emitAllocCN(SizeT, Desc, IsNoThrow, E))
3184           return false;
3185       }
3186     }
3187 
3188     if (Init && !this->visitInitializer(Init))
3189       return false;
3190 
3191   } else {
3192     if (PlacementDest) {
3193       if (!this->visit(PlacementDest))
3194         return false;
3195       if (!this->emitCheckNewTypeMismatch(E, E))
3196         return false;
3197     } else {
3198       // Allocate just one element.
3199       if (!this->emitAlloc(Desc, E))
3200         return false;
3201     }
3202 
3203     if (Init) {
3204       if (ElemT) {
3205         if (!this->visit(Init))
3206           return false;
3207 
3208         if (!this->emitInit(*ElemT, E))
3209           return false;
3210       } else {
3211         // Composite.
3212         if (!this->visitInitializer(Init))
3213           return false;
3214       }
3215     }
3216   }
3217 
3218   if (DiscardResult)
3219     return this->emitPopPtr(E);
3220 
3221   return true;
3222 }
3223 
3224 template <class Emitter>
3225 bool Compiler<Emitter>::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
3226   const Expr *Arg = E->getArgument();
3227 
3228   const FunctionDecl *OperatorDelete = E->getOperatorDelete();
3229 
3230   if (!OperatorDelete->isReplaceableGlobalAllocationFunction())
3231     return this->emitInvalidNewDeleteExpr(E, E);
3232 
3233   // Arg must be an lvalue.
3234   if (!this->visit(Arg))
3235     return false;
3236 
3237   return this->emitFree(E->isArrayForm(), E);
3238 }
3239 
3240 template <class Emitter>
3241 bool Compiler<Emitter>::VisitBlockExpr(const BlockExpr *E) {
3242   const Function *Func = nullptr;
3243   if (auto F = Compiler<ByteCodeEmitter>(Ctx, P).compileObjCBlock(E))
3244     Func = F;
3245 
3246   if (!Func)
3247     return false;
3248   return this->emitGetFnPtr(Func, E);
3249 }
3250 
3251 template <class Emitter>
3252 bool Compiler<Emitter>::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3253   assert(Ctx.getLangOpts().CPlusPlus);
3254   return this->emitConstBool(E->getValue(), E);
3255 }
3256 
3257 template <class Emitter>
3258 bool Compiler<Emitter>::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
3259   if (DiscardResult)
3260     return true;
3261   assert(!Initializing);
3262 
3263   const MSGuidDecl *GuidDecl = E->getGuidDecl();
3264   const RecordDecl *RD = GuidDecl->getType()->getAsRecordDecl();
3265   assert(RD);
3266   // If the definiton of the result type is incomplete, just return a dummy.
3267   // If (and when) that is read from, we will fail, but not now.
3268   if (!RD->isCompleteDefinition()) {
3269     if (std::optional<unsigned> I = P.getOrCreateDummy(GuidDecl))
3270       return this->emitGetPtrGlobal(*I, E);
3271     return false;
3272   }
3273 
3274   std::optional<unsigned> GlobalIndex = P.getOrCreateGlobal(GuidDecl);
3275   if (!GlobalIndex)
3276     return false;
3277   if (!this->emitGetPtrGlobal(*GlobalIndex, E))
3278     return false;
3279 
3280   assert(this->getRecord(E->getType()));
3281 
3282   const APValue &V = GuidDecl->getAsAPValue();
3283   if (V.getKind() == APValue::None)
3284     return true;
3285 
3286   assert(V.isStruct());
3287   assert(V.getStructNumBases() == 0);
3288   if (!this->visitAPValueInitializer(V, E))
3289     return false;
3290 
3291   return this->emitFinishInit(E);
3292 }
3293 
3294 template <class Emitter>
3295 bool Compiler<Emitter>::VisitRequiresExpr(const RequiresExpr *E) {
3296   assert(classifyPrim(E->getType()) == PT_Bool);
3297   if (DiscardResult)
3298     return true;
3299   return this->emitConstBool(E->isSatisfied(), E);
3300 }
3301 
3302 template <class Emitter>
3303 bool Compiler<Emitter>::VisitConceptSpecializationExpr(
3304     const ConceptSpecializationExpr *E) {
3305   assert(classifyPrim(E->getType()) == PT_Bool);
3306   if (DiscardResult)
3307     return true;
3308   return this->emitConstBool(E->isSatisfied(), E);
3309 }
3310 
3311 template <class Emitter>
3312 bool Compiler<Emitter>::VisitCXXRewrittenBinaryOperator(
3313     const CXXRewrittenBinaryOperator *E) {
3314   return this->delegate(E->getSemanticForm());
3315 }
3316 
3317 template <class Emitter>
3318 bool Compiler<Emitter>::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
3319 
3320   for (const Expr *SemE : E->semantics()) {
3321     if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
3322       if (SemE == E->getResultExpr())
3323         return false;
3324 
3325       if (OVE->isUnique())
3326         continue;
3327 
3328       if (!this->discard(OVE))
3329         return false;
3330     } else if (SemE == E->getResultExpr()) {
3331       if (!this->delegate(SemE))
3332         return false;
3333     } else {
3334       if (!this->discard(SemE))
3335         return false;
3336     }
3337   }
3338   return true;
3339 }
3340 
3341 template <class Emitter>
3342 bool Compiler<Emitter>::VisitPackIndexingExpr(const PackIndexingExpr *E) {
3343   return this->delegate(E->getSelectedExpr());
3344 }
3345 
3346 template <class Emitter>
3347 bool Compiler<Emitter>::VisitRecoveryExpr(const RecoveryExpr *E) {
3348   return this->emitError(E);
3349 }
3350 
3351 template <class Emitter>
3352 bool Compiler<Emitter>::VisitAddrLabelExpr(const AddrLabelExpr *E) {
3353   assert(E->getType()->isVoidPointerType());
3354 
3355   unsigned Offset = allocateLocalPrimitive(
3356       E->getLabel(), PT_Ptr, /*IsConst=*/true, /*IsExtended=*/false);
3357 
3358   return this->emitGetLocal(PT_Ptr, Offset, E);
3359 }
3360 
3361 template <class Emitter>
3362 bool Compiler<Emitter>::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
3363   assert(Initializing);
3364   const auto *VT = E->getType()->castAs<VectorType>();
3365   QualType ElemType = VT->getElementType();
3366   PrimType ElemT = classifyPrim(ElemType);
3367   const Expr *Src = E->getSrcExpr();
3368   PrimType SrcElemT =
3369       classifyPrim(Src->getType()->castAs<VectorType>()->getElementType());
3370 
3371   unsigned SrcOffset = this->allocateLocalPrimitive(Src, PT_Ptr, true, false);
3372   if (!this->visit(Src))
3373     return false;
3374   if (!this->emitSetLocal(PT_Ptr, SrcOffset, E))
3375     return false;
3376 
3377   for (unsigned I = 0; I != VT->getNumElements(); ++I) {
3378     if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
3379       return false;
3380     if (!this->emitArrayElemPop(SrcElemT, I, E))
3381       return false;
3382     if (SrcElemT != ElemT) {
3383       if (!this->emitPrimCast(SrcElemT, ElemT, ElemType, E))
3384         return false;
3385     }
3386     if (!this->emitInitElem(ElemT, I, E))
3387       return false;
3388   }
3389 
3390   return true;
3391 }
3392 
3393 template <class Emitter>
3394 bool Compiler<Emitter>::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
3395   assert(Initializing);
3396   assert(E->getNumSubExprs() > 2);
3397 
3398   const Expr *Vecs[] = {E->getExpr(0), E->getExpr(1)};
3399   const VectorType *VT = Vecs[0]->getType()->castAs<VectorType>();
3400   PrimType ElemT = classifyPrim(VT->getElementType());
3401   unsigned NumInputElems = VT->getNumElements();
3402   unsigned NumOutputElems = E->getNumSubExprs() - 2;
3403   assert(NumOutputElems > 0);
3404 
3405   // Save both input vectors to a local variable.
3406   unsigned VectorOffsets[2];
3407   for (unsigned I = 0; I != 2; ++I) {
3408     VectorOffsets[I] = this->allocateLocalPrimitive(
3409         Vecs[I], PT_Ptr, /*IsConst=*/true, /*IsExtended=*/false);
3410     if (!this->visit(Vecs[I]))
3411       return false;
3412     if (!this->emitSetLocal(PT_Ptr, VectorOffsets[I], E))
3413       return false;
3414   }
3415   for (unsigned I = 0; I != NumOutputElems; ++I) {
3416     APSInt ShuffleIndex = E->getShuffleMaskIdx(Ctx.getASTContext(), I);
3417     if (ShuffleIndex == -1)
3418       return this->emitInvalid(E); // FIXME: Better diagnostic.
3419 
3420     assert(ShuffleIndex < (NumInputElems * 2));
3421     if (!this->emitGetLocal(PT_Ptr,
3422                             VectorOffsets[ShuffleIndex >= NumInputElems], E))
3423       return false;
3424     unsigned InputVectorIndex = ShuffleIndex.getZExtValue() % NumInputElems;
3425     if (!this->emitArrayElemPop(ElemT, InputVectorIndex, E))
3426       return false;
3427 
3428     if (!this->emitInitElem(ElemT, I, E))
3429       return false;
3430   }
3431 
3432   return true;
3433 }
3434 
3435 template <class Emitter>
3436 bool Compiler<Emitter>::VisitExtVectorElementExpr(
3437     const ExtVectorElementExpr *E) {
3438   const Expr *Base = E->getBase();
3439   assert(
3440       Base->getType()->isVectorType() ||
3441       Base->getType()->getAs<PointerType>()->getPointeeType()->isVectorType());
3442 
3443   SmallVector<uint32_t, 4> Indices;
3444   E->getEncodedElementAccess(Indices);
3445 
3446   if (Indices.size() == 1) {
3447     if (!this->visit(Base))
3448       return false;
3449 
3450     if (E->isGLValue()) {
3451       if (!this->emitConstUint32(Indices[0], E))
3452         return false;
3453       return this->emitArrayElemPtrPop(PT_Uint32, E);
3454     }
3455     // Else, also load the value.
3456     return this->emitArrayElemPop(classifyPrim(E->getType()), Indices[0], E);
3457   }
3458 
3459   // Create a local variable for the base.
3460   unsigned BaseOffset = allocateLocalPrimitive(Base, PT_Ptr, /*IsConst=*/true,
3461                                                /*IsExtended=*/false);
3462   if (!this->visit(Base))
3463     return false;
3464   if (!this->emitSetLocal(PT_Ptr, BaseOffset, E))
3465     return false;
3466 
3467   // Now the vector variable for the return value.
3468   if (!Initializing) {
3469     std::optional<unsigned> ResultIndex;
3470     ResultIndex = allocateLocal(E);
3471     if (!ResultIndex)
3472       return false;
3473     if (!this->emitGetPtrLocal(*ResultIndex, E))
3474       return false;
3475   }
3476 
3477   assert(Indices.size() == E->getType()->getAs<VectorType>()->getNumElements());
3478 
3479   PrimType ElemT =
3480       classifyPrim(E->getType()->getAs<VectorType>()->getElementType());
3481   uint32_t DstIndex = 0;
3482   for (uint32_t I : Indices) {
3483     if (!this->emitGetLocal(PT_Ptr, BaseOffset, E))
3484       return false;
3485     if (!this->emitArrayElemPop(ElemT, I, E))
3486       return false;
3487     if (!this->emitInitElem(ElemT, DstIndex, E))
3488       return false;
3489     ++DstIndex;
3490   }
3491 
3492   // Leave the result pointer on the stack.
3493   assert(!DiscardResult);
3494   return true;
3495 }
3496 
3497 template <class Emitter>
3498 bool Compiler<Emitter>::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
3499   const Expr *SubExpr = E->getSubExpr();
3500   if (!E->isExpressibleAsConstantInitializer())
3501     return this->discard(SubExpr) && this->emitInvalid(E);
3502 
3503   assert(classifyPrim(E) == PT_Ptr);
3504   if (std::optional<unsigned> I = P.getOrCreateDummy(E))
3505     return this->emitGetPtrGlobal(*I, E);
3506 
3507   return false;
3508 }
3509 
3510 template <class Emitter>
3511 bool Compiler<Emitter>::VisitCXXStdInitializerListExpr(
3512     const CXXStdInitializerListExpr *E) {
3513   const Expr *SubExpr = E->getSubExpr();
3514   const ConstantArrayType *ArrayType =
3515       Ctx.getASTContext().getAsConstantArrayType(SubExpr->getType());
3516   const Record *R = getRecord(E->getType());
3517   assert(Initializing);
3518   assert(SubExpr->isGLValue());
3519 
3520   if (!this->visit(SubExpr))
3521     return false;
3522   if (!this->emitConstUint8(0, E))
3523     return false;
3524   if (!this->emitArrayElemPtrPopUint8(E))
3525     return false;
3526   if (!this->emitInitFieldPtr(R->getField(0u)->Offset, E))
3527     return false;
3528 
3529   PrimType SecondFieldT = classifyPrim(R->getField(1u)->Decl->getType());
3530   if (isIntegralType(SecondFieldT)) {
3531     if (!this->emitConst(static_cast<APSInt>(ArrayType->getSize()),
3532                          SecondFieldT, E))
3533       return false;
3534     return this->emitInitField(SecondFieldT, R->getField(1u)->Offset, E);
3535   }
3536   assert(SecondFieldT == PT_Ptr);
3537 
3538   if (!this->emitGetFieldPtr(R->getField(0u)->Offset, E))
3539     return false;
3540   if (!this->emitExpandPtr(E))
3541     return false;
3542   if (!this->emitConst(static_cast<APSInt>(ArrayType->getSize()), PT_Uint64, E))
3543     return false;
3544   if (!this->emitArrayElemPtrPop(PT_Uint64, E))
3545     return false;
3546   return this->emitInitFieldPtr(R->getField(1u)->Offset, E);
3547 }
3548 
3549 template <class Emitter>
3550 bool Compiler<Emitter>::VisitStmtExpr(const StmtExpr *E) {
3551   BlockScope<Emitter> BS(this);
3552   StmtExprScope<Emitter> SS(this);
3553 
3554   const CompoundStmt *CS = E->getSubStmt();
3555   const Stmt *Result = CS->getStmtExprResult();
3556   for (const Stmt *S : CS->body()) {
3557     if (S != Result) {
3558       if (!this->visitStmt(S))
3559         return false;
3560       continue;
3561     }
3562 
3563     assert(S == Result);
3564     if (const Expr *ResultExpr = dyn_cast<Expr>(S))
3565       return this->delegate(ResultExpr);
3566     return this->emitUnsupported(E);
3567   }
3568 
3569   return BS.destroyLocals();
3570 }
3571 
3572 template <class Emitter> bool Compiler<Emitter>::discard(const Expr *E) {
3573   OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/true,
3574                              /*NewInitializing=*/false);
3575   return this->Visit(E);
3576 }
3577 
3578 template <class Emitter> bool Compiler<Emitter>::delegate(const Expr *E) {
3579   // We're basically doing:
3580   // OptionScope<Emitter> Scope(this, DicardResult, Initializing);
3581   // but that's unnecessary of course.
3582   return this->Visit(E);
3583 }
3584 
3585 template <class Emitter> bool Compiler<Emitter>::visit(const Expr *E) {
3586   if (E->getType().isNull())
3587     return false;
3588 
3589   if (E->getType()->isVoidType())
3590     return this->discard(E);
3591 
3592   // Create local variable to hold the return value.
3593   if (!E->isGLValue() && !E->getType()->isAnyComplexType() &&
3594       !classify(E->getType())) {
3595     std::optional<unsigned> LocalIndex = allocateLocal(E);
3596     if (!LocalIndex)
3597       return false;
3598 
3599     if (!this->emitGetPtrLocal(*LocalIndex, E))
3600       return false;
3601     return this->visitInitializer(E);
3602   }
3603 
3604   //  Otherwise,we have a primitive return value, produce the value directly
3605   //  and push it on the stack.
3606   OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
3607                              /*NewInitializing=*/false);
3608   return this->Visit(E);
3609 }
3610 
3611 template <class Emitter>
3612 bool Compiler<Emitter>::visitInitializer(const Expr *E) {
3613   assert(!classify(E->getType()));
3614 
3615   OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
3616                              /*NewInitializing=*/true);
3617   return this->Visit(E);
3618 }
3619 
3620 template <class Emitter> bool Compiler<Emitter>::visitBool(const Expr *E) {
3621   std::optional<PrimType> T = classify(E->getType());
3622   if (!T) {
3623     // Convert complex values to bool.
3624     if (E->getType()->isAnyComplexType()) {
3625       if (!this->visit(E))
3626         return false;
3627       return this->emitComplexBoolCast(E);
3628     }
3629     return false;
3630   }
3631 
3632   if (!this->visit(E))
3633     return false;
3634 
3635   if (T == PT_Bool)
3636     return true;
3637 
3638   // Convert pointers to bool.
3639   if (T == PT_Ptr || T == PT_FnPtr) {
3640     if (!this->emitNull(*T, nullptr, E))
3641       return false;
3642     return this->emitNE(*T, E);
3643   }
3644 
3645   // Or Floats.
3646   if (T == PT_Float)
3647     return this->emitCastFloatingIntegralBool(getFPOptions(E), E);
3648 
3649   // Or anything else we can.
3650   return this->emitCast(*T, PT_Bool, E);
3651 }
3652 
3653 template <class Emitter>
3654 bool Compiler<Emitter>::visitZeroInitializer(PrimType T, QualType QT,
3655                                              const Expr *E) {
3656   switch (T) {
3657   case PT_Bool:
3658     return this->emitZeroBool(E);
3659   case PT_Sint8:
3660     return this->emitZeroSint8(E);
3661   case PT_Uint8:
3662     return this->emitZeroUint8(E);
3663   case PT_Sint16:
3664     return this->emitZeroSint16(E);
3665   case PT_Uint16:
3666     return this->emitZeroUint16(E);
3667   case PT_Sint32:
3668     return this->emitZeroSint32(E);
3669   case PT_Uint32:
3670     return this->emitZeroUint32(E);
3671   case PT_Sint64:
3672     return this->emitZeroSint64(E);
3673   case PT_Uint64:
3674     return this->emitZeroUint64(E);
3675   case PT_IntAP:
3676     return this->emitZeroIntAP(Ctx.getBitWidth(QT), E);
3677   case PT_IntAPS:
3678     return this->emitZeroIntAPS(Ctx.getBitWidth(QT), E);
3679   case PT_Ptr:
3680     return this->emitNullPtr(nullptr, E);
3681   case PT_FnPtr:
3682     return this->emitNullFnPtr(nullptr, E);
3683   case PT_MemberPtr:
3684     return this->emitNullMemberPtr(nullptr, E);
3685   case PT_Float: {
3686     return this->emitConstFloat(APFloat::getZero(Ctx.getFloatSemantics(QT)), E);
3687   }
3688   }
3689   llvm_unreachable("unknown primitive type");
3690 }
3691 
3692 template <class Emitter>
3693 bool Compiler<Emitter>::visitZeroRecordInitializer(const Record *R,
3694                                                    const Expr *E) {
3695   assert(E);
3696   assert(R);
3697   // Fields
3698   for (const Record::Field &Field : R->fields()) {
3699     if (Field.Decl->isUnnamedBitField())
3700       continue;
3701 
3702     const Descriptor *D = Field.Desc;
3703     if (D->isPrimitive()) {
3704       QualType QT = D->getType();
3705       PrimType T = classifyPrim(D->getType());
3706       if (!this->visitZeroInitializer(T, QT, E))
3707         return false;
3708       if (!this->emitInitField(T, Field.Offset, E))
3709         return false;
3710       if (R->isUnion())
3711         break;
3712       continue;
3713     }
3714 
3715     if (!this->emitGetPtrField(Field.Offset, E))
3716       return false;
3717 
3718     if (D->isPrimitiveArray()) {
3719       QualType ET = D->getElemQualType();
3720       PrimType T = classifyPrim(ET);
3721       for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) {
3722         if (!this->visitZeroInitializer(T, ET, E))
3723           return false;
3724         if (!this->emitInitElem(T, I, E))
3725           return false;
3726       }
3727     } else if (D->isCompositeArray()) {
3728       const Record *ElemRecord = D->ElemDesc->ElemRecord;
3729       assert(D->ElemDesc->ElemRecord);
3730       for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) {
3731         if (!this->emitConstUint32(I, E))
3732           return false;
3733         if (!this->emitArrayElemPtr(PT_Uint32, E))
3734           return false;
3735         if (!this->visitZeroRecordInitializer(ElemRecord, E))
3736           return false;
3737         if (!this->emitPopPtr(E))
3738           return false;
3739       }
3740     } else if (D->isRecord()) {
3741       if (!this->visitZeroRecordInitializer(D->ElemRecord, E))
3742         return false;
3743     } else {
3744       assert(false);
3745     }
3746 
3747     if (!this->emitFinishInitPop(E))
3748       return false;
3749 
3750     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3751     // object's first non-static named data member is zero-initialized
3752     if (R->isUnion())
3753       break;
3754   }
3755 
3756   for (const Record::Base &B : R->bases()) {
3757     if (!this->emitGetPtrBase(B.Offset, E))
3758       return false;
3759     if (!this->visitZeroRecordInitializer(B.R, E))
3760       return false;
3761     if (!this->emitFinishInitPop(E))
3762       return false;
3763   }
3764 
3765   // FIXME: Virtual bases.
3766 
3767   return true;
3768 }
3769 
3770 template <class Emitter>
3771 template <typename T>
3772 bool Compiler<Emitter>::emitConst(T Value, PrimType Ty, const Expr *E) {
3773   switch (Ty) {
3774   case PT_Sint8:
3775     return this->emitConstSint8(Value, E);
3776   case PT_Uint8:
3777     return this->emitConstUint8(Value, E);
3778   case PT_Sint16:
3779     return this->emitConstSint16(Value, E);
3780   case PT_Uint16:
3781     return this->emitConstUint16(Value, E);
3782   case PT_Sint32:
3783     return this->emitConstSint32(Value, E);
3784   case PT_Uint32:
3785     return this->emitConstUint32(Value, E);
3786   case PT_Sint64:
3787     return this->emitConstSint64(Value, E);
3788   case PT_Uint64:
3789     return this->emitConstUint64(Value, E);
3790   case PT_Bool:
3791     return this->emitConstBool(Value, E);
3792   case PT_Ptr:
3793   case PT_FnPtr:
3794   case PT_MemberPtr:
3795   case PT_Float:
3796   case PT_IntAP:
3797   case PT_IntAPS:
3798     llvm_unreachable("Invalid integral type");
3799     break;
3800   }
3801   llvm_unreachable("unknown primitive type");
3802 }
3803 
3804 template <class Emitter>
3805 template <typename T>
3806 bool Compiler<Emitter>::emitConst(T Value, const Expr *E) {
3807   return this->emitConst(Value, classifyPrim(E->getType()), E);
3808 }
3809 
3810 template <class Emitter>
3811 bool Compiler<Emitter>::emitConst(const APSInt &Value, PrimType Ty,
3812                                   const Expr *E) {
3813   if (Ty == PT_IntAPS)
3814     return this->emitConstIntAPS(Value, E);
3815   if (Ty == PT_IntAP)
3816     return this->emitConstIntAP(Value, E);
3817 
3818   if (Value.isSigned())
3819     return this->emitConst(Value.getSExtValue(), Ty, E);
3820   return this->emitConst(Value.getZExtValue(), Ty, E);
3821 }
3822 
3823 template <class Emitter>
3824 bool Compiler<Emitter>::emitConst(const APSInt &Value, const Expr *E) {
3825   return this->emitConst(Value, classifyPrim(E->getType()), E);
3826 }
3827 
3828 template <class Emitter>
3829 unsigned Compiler<Emitter>::allocateLocalPrimitive(DeclTy &&Src, PrimType Ty,
3830                                                    bool IsConst,
3831                                                    bool IsExtended) {
3832   // Make sure we don't accidentally register the same decl twice.
3833   if (const auto *VD =
3834           dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) {
3835     assert(!P.getGlobal(VD));
3836     assert(!Locals.contains(VD));
3837     (void)VD;
3838   }
3839 
3840   // FIXME: There are cases where Src.is<Expr*>() is wrong, e.g.
3841   //   (int){12} in C. Consider using Expr::isTemporaryObject() instead
3842   //   or isa<MaterializeTemporaryExpr>().
3843   Descriptor *D = P.createDescriptor(Src, Ty, Descriptor::InlineDescMD, IsConst,
3844                                      Src.is<const Expr *>());
3845   Scope::Local Local = this->createLocal(D);
3846   if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>()))
3847     Locals.insert({VD, Local});
3848   VarScope->add(Local, IsExtended);
3849   return Local.Offset;
3850 }
3851 
3852 template <class Emitter>
3853 std::optional<unsigned>
3854 Compiler<Emitter>::allocateLocal(DeclTy &&Src, const ValueDecl *ExtendingDecl) {
3855   // Make sure we don't accidentally register the same decl twice.
3856   if ([[maybe_unused]] const auto *VD =
3857           dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) {
3858     assert(!P.getGlobal(VD));
3859     assert(!Locals.contains(VD));
3860   }
3861 
3862   QualType Ty;
3863   const ValueDecl *Key = nullptr;
3864   const Expr *Init = nullptr;
3865   bool IsTemporary = false;
3866   if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) {
3867     Key = VD;
3868     Ty = VD->getType();
3869 
3870     if (const auto *VarD = dyn_cast<VarDecl>(VD))
3871       Init = VarD->getInit();
3872   }
3873   if (auto *E = Src.dyn_cast<const Expr *>()) {
3874     IsTemporary = true;
3875     Ty = E->getType();
3876   }
3877 
3878   Descriptor *D = P.createDescriptor(
3879       Src, Ty.getTypePtr(), Descriptor::InlineDescMD, Ty.isConstQualified(),
3880       IsTemporary, /*IsMutable=*/false, Init);
3881   if (!D)
3882     return std::nullopt;
3883 
3884   Scope::Local Local = this->createLocal(D);
3885   if (Key)
3886     Locals.insert({Key, Local});
3887   if (ExtendingDecl)
3888     VarScope->addExtended(Local, ExtendingDecl);
3889   else
3890     VarScope->add(Local, false);
3891   return Local.Offset;
3892 }
3893 
3894 template <class Emitter>
3895 unsigned Compiler<Emitter>::allocateTemporary(const Expr *E) {
3896   QualType Ty = E->getType();
3897   assert(!Ty->isRecordType());
3898 
3899   Descriptor *D = P.createDescriptor(
3900       E, Ty.getTypePtr(), Descriptor::InlineDescMD, Ty.isConstQualified(),
3901       /*IsTemporary=*/true, /*IsMutable=*/false, /*Init=*/nullptr);
3902   assert(D);
3903 
3904   Scope::Local Local = this->createLocal(D);
3905   VariableScope<Emitter> *S = VarScope;
3906   assert(S);
3907   // Attach to topmost scope.
3908   while (S->getParent())
3909     S = S->getParent();
3910   assert(S && !S->getParent());
3911   S->addLocal(Local);
3912   return Local.Offset;
3913 }
3914 
3915 template <class Emitter>
3916 const RecordType *Compiler<Emitter>::getRecordTy(QualType Ty) {
3917   if (const PointerType *PT = dyn_cast<PointerType>(Ty))
3918     return PT->getPointeeType()->getAs<RecordType>();
3919   return Ty->getAs<RecordType>();
3920 }
3921 
3922 template <class Emitter> Record *Compiler<Emitter>::getRecord(QualType Ty) {
3923   if (const auto *RecordTy = getRecordTy(Ty))
3924     return getRecord(RecordTy->getDecl());
3925   return nullptr;
3926 }
3927 
3928 template <class Emitter>
3929 Record *Compiler<Emitter>::getRecord(const RecordDecl *RD) {
3930   return P.getOrCreateRecord(RD);
3931 }
3932 
3933 template <class Emitter>
3934 const Function *Compiler<Emitter>::getFunction(const FunctionDecl *FD) {
3935   return Ctx.getOrCreateFunction(FD);
3936 }
3937 
3938 template <class Emitter>
3939 bool Compiler<Emitter>::visitExpr(const Expr *E, bool DestroyToplevelScope) {
3940   LocalScope<Emitter> RootScope(this);
3941 
3942   auto maybeDestroyLocals = [&]() -> bool {
3943     if (DestroyToplevelScope)
3944       return RootScope.destroyLocals();
3945     return true;
3946   };
3947 
3948   // Void expressions.
3949   if (E->getType()->isVoidType()) {
3950     if (!visit(E))
3951       return false;
3952     return this->emitRetVoid(E) && maybeDestroyLocals();
3953   }
3954 
3955   // Expressions with a primitive return type.
3956   if (std::optional<PrimType> T = classify(E)) {
3957     if (!visit(E))
3958       return false;
3959 
3960     return this->emitRet(*T, E) && maybeDestroyLocals();
3961   }
3962 
3963   // Expressions with a composite return type.
3964   // For us, that means everything we don't
3965   // have a PrimType for.
3966   if (std::optional<unsigned> LocalOffset = this->allocateLocal(E)) {
3967     if (!this->emitGetPtrLocal(*LocalOffset, E))
3968       return false;
3969 
3970     if (!visitInitializer(E))
3971       return false;
3972 
3973     if (!this->emitFinishInit(E))
3974       return false;
3975     // We are destroying the locals AFTER the Ret op.
3976     // The Ret op needs to copy the (alive) values, but the
3977     // destructors may still turn the entire expression invalid.
3978     return this->emitRetValue(E) && maybeDestroyLocals();
3979   }
3980 
3981   (void)maybeDestroyLocals();
3982   return false;
3983 }
3984 
3985 template <class Emitter>
3986 VarCreationState Compiler<Emitter>::visitDecl(const VarDecl *VD) {
3987 
3988   auto R = this->visitVarDecl(VD, /*Toplevel=*/true);
3989 
3990   if (R.notCreated())
3991     return R;
3992 
3993   if (R)
3994     return true;
3995 
3996   if (!R && Context::shouldBeGloballyIndexed(VD)) {
3997     if (auto GlobalIndex = P.getGlobal(VD)) {
3998       Block *GlobalBlock = P.getGlobal(*GlobalIndex);
3999       GlobalInlineDescriptor &GD =
4000           *reinterpret_cast<GlobalInlineDescriptor *>(GlobalBlock->rawData());
4001 
4002       GD.InitState = GlobalInitState::InitializerFailed;
4003       GlobalBlock->invokeDtor();
4004     }
4005   }
4006 
4007   return R;
4008 }
4009 
4010 /// Toplevel visitDeclAndReturn().
4011 /// We get here from evaluateAsInitializer().
4012 /// We need to evaluate the initializer and return its value.
4013 template <class Emitter>
4014 bool Compiler<Emitter>::visitDeclAndReturn(const VarDecl *VD,
4015                                            bool ConstantContext) {
4016   std::optional<PrimType> VarT = classify(VD->getType());
4017 
4018   // We only create variables if we're evaluating in a constant context.
4019   // Otherwise, just evaluate the initializer and return it.
4020   if (!ConstantContext) {
4021     DeclScope<Emitter> LS(this, VD);
4022     if (!this->visit(VD->getAnyInitializer()))
4023       return false;
4024     return this->emitRet(VarT.value_or(PT_Ptr), VD) && LS.destroyLocals();
4025   }
4026 
4027   LocalScope<Emitter> VDScope(this, VD);
4028   if (!this->visitVarDecl(VD, /*Toplevel=*/true))
4029     return false;
4030 
4031   if (Context::shouldBeGloballyIndexed(VD)) {
4032     auto GlobalIndex = P.getGlobal(VD);
4033     assert(GlobalIndex); // visitVarDecl() didn't return false.
4034     if (VarT) {
4035       if (!this->emitGetGlobalUnchecked(*VarT, *GlobalIndex, VD))
4036         return false;
4037     } else {
4038       if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
4039         return false;
4040     }
4041   } else {
4042     auto Local = Locals.find(VD);
4043     assert(Local != Locals.end()); // Same here.
4044     if (VarT) {
4045       if (!this->emitGetLocal(*VarT, Local->second.Offset, VD))
4046         return false;
4047     } else {
4048       if (!this->emitGetPtrLocal(Local->second.Offset, VD))
4049         return false;
4050     }
4051   }
4052 
4053   // Return the value.
4054   if (!this->emitRet(VarT.value_or(PT_Ptr), VD)) {
4055     // If the Ret above failed and this is a global variable, mark it as
4056     // uninitialized, even everything else succeeded.
4057     if (Context::shouldBeGloballyIndexed(VD)) {
4058       auto GlobalIndex = P.getGlobal(VD);
4059       assert(GlobalIndex);
4060       Block *GlobalBlock = P.getGlobal(*GlobalIndex);
4061       GlobalInlineDescriptor &GD =
4062           *reinterpret_cast<GlobalInlineDescriptor *>(GlobalBlock->rawData());
4063 
4064       GD.InitState = GlobalInitState::InitializerFailed;
4065       GlobalBlock->invokeDtor();
4066     }
4067     return false;
4068   }
4069 
4070   return VDScope.destroyLocals();
4071 }
4072 
4073 template <class Emitter>
4074 VarCreationState Compiler<Emitter>::visitVarDecl(const VarDecl *VD,
4075                                                  bool Toplevel) {
4076   // We don't know what to do with these, so just return false.
4077   if (VD->getType().isNull())
4078     return false;
4079 
4080   // This case is EvalEmitter-only. If we won't create any instructions for the
4081   // initializer anyway, don't bother creating the variable in the first place.
4082   if (!this->isActive())
4083     return VarCreationState::NotCreated();
4084 
4085   const Expr *Init = VD->getInit();
4086   std::optional<PrimType> VarT = classify(VD->getType());
4087 
4088   if (Init && Init->isValueDependent())
4089     return false;
4090 
4091   if (Context::shouldBeGloballyIndexed(VD)) {
4092     auto checkDecl = [&]() -> bool {
4093       bool NeedsOp = !Toplevel && VD->isLocalVarDecl() && VD->isStaticLocal();
4094       return !NeedsOp || this->emitCheckDecl(VD, VD);
4095     };
4096 
4097     auto initGlobal = [&](unsigned GlobalIndex) -> bool {
4098       assert(Init);
4099 
4100       if (VarT) {
4101         if (!this->visit(Init))
4102           return checkDecl() && false;
4103 
4104         return checkDecl() && this->emitInitGlobal(*VarT, GlobalIndex, VD);
4105       }
4106 
4107       if (!checkDecl())
4108         return false;
4109 
4110       if (!this->emitGetPtrGlobal(GlobalIndex, Init))
4111         return false;
4112 
4113       if (!visitInitializer(Init))
4114         return false;
4115 
4116       if (!this->emitFinishInit(Init))
4117         return false;
4118 
4119       return this->emitPopPtr(Init);
4120     };
4121 
4122     DeclScope<Emitter> LocalScope(this, VD);
4123 
4124     // We've already seen and initialized this global.
4125     if (std::optional<unsigned> GlobalIndex = P.getGlobal(VD)) {
4126       if (P.getPtrGlobal(*GlobalIndex).isInitialized())
4127         return checkDecl();
4128 
4129       // The previous attempt at initialization might've been unsuccessful,
4130       // so let's try this one.
4131       return Init && checkDecl() && initGlobal(*GlobalIndex);
4132     }
4133 
4134     std::optional<unsigned> GlobalIndex = P.createGlobal(VD, Init);
4135 
4136     if (!GlobalIndex)
4137       return false;
4138 
4139     return !Init || (checkDecl() && initGlobal(*GlobalIndex));
4140   } else {
4141     InitLinkScope<Emitter> ILS(this, InitLink::Decl(VD));
4142 
4143     if (VarT) {
4144       unsigned Offset = this->allocateLocalPrimitive(
4145           VD, *VarT, VD->getType().isConstQualified());
4146       if (Init) {
4147         // If this is a toplevel declaration, create a scope for the
4148         // initializer.
4149         if (Toplevel) {
4150           LocalScope<Emitter> Scope(this);
4151           if (!this->visit(Init))
4152             return false;
4153           return this->emitSetLocal(*VarT, Offset, VD) && Scope.destroyLocals();
4154         } else {
4155           if (!this->visit(Init))
4156             return false;
4157           return this->emitSetLocal(*VarT, Offset, VD);
4158         }
4159       }
4160     } else {
4161       if (std::optional<unsigned> Offset = this->allocateLocal(VD)) {
4162         if (!Init)
4163           return true;
4164 
4165         if (!this->emitGetPtrLocal(*Offset, Init))
4166           return false;
4167 
4168         if (!visitInitializer(Init))
4169           return false;
4170 
4171         if (!this->emitFinishInit(Init))
4172           return false;
4173 
4174         return this->emitPopPtr(Init);
4175       }
4176       return false;
4177     }
4178     return true;
4179   }
4180 
4181   return false;
4182 }
4183 
4184 template <class Emitter>
4185 bool Compiler<Emitter>::visitAPValue(const APValue &Val, PrimType ValType,
4186                                      const Expr *E) {
4187   assert(!DiscardResult);
4188   if (Val.isInt())
4189     return this->emitConst(Val.getInt(), ValType, E);
4190   else if (Val.isFloat())
4191     return this->emitConstFloat(Val.getFloat(), E);
4192 
4193   if (Val.isLValue()) {
4194     if (Val.isNullPointer())
4195       return this->emitNull(ValType, nullptr, E);
4196     APValue::LValueBase Base = Val.getLValueBase();
4197     if (const Expr *BaseExpr = Base.dyn_cast<const Expr *>())
4198       return this->visit(BaseExpr);
4199     else if (const auto *VD = Base.dyn_cast<const ValueDecl *>()) {
4200       return this->visitDeclRef(VD, E);
4201     }
4202   } else if (Val.isMemberPointer()) {
4203     if (const ValueDecl *MemberDecl = Val.getMemberPointerDecl())
4204       return this->emitGetMemberPtr(MemberDecl, E);
4205     return this->emitNullMemberPtr(nullptr, E);
4206   }
4207 
4208   return false;
4209 }
4210 
4211 template <class Emitter>
4212 bool Compiler<Emitter>::visitAPValueInitializer(const APValue &Val,
4213                                                 const Expr *E) {
4214 
4215   if (Val.isStruct()) {
4216     const Record *R = this->getRecord(E->getType());
4217     assert(R);
4218     for (unsigned I = 0, N = Val.getStructNumFields(); I != N; ++I) {
4219       const APValue &F = Val.getStructField(I);
4220       const Record::Field *RF = R->getField(I);
4221 
4222       if (F.isInt() || F.isFloat() || F.isLValue() || F.isMemberPointer()) {
4223         PrimType T = classifyPrim(RF->Decl->getType());
4224         if (!this->visitAPValue(F, T, E))
4225           return false;
4226         if (!this->emitInitField(T, RF->Offset, E))
4227           return false;
4228       } else if (F.isArray()) {
4229         assert(RF->Desc->isPrimitiveArray());
4230         const auto *ArrType = RF->Decl->getType()->getAsArrayTypeUnsafe();
4231         PrimType ElemT = classifyPrim(ArrType->getElementType());
4232         assert(ArrType);
4233 
4234         if (!this->emitGetPtrField(RF->Offset, E))
4235           return false;
4236 
4237         for (unsigned A = 0, AN = F.getArraySize(); A != AN; ++A) {
4238           if (!this->visitAPValue(F.getArrayInitializedElt(A), ElemT, E))
4239             return false;
4240           if (!this->emitInitElem(ElemT, A, E))
4241             return false;
4242         }
4243 
4244         if (!this->emitPopPtr(E))
4245           return false;
4246       } else if (F.isStruct() || F.isUnion()) {
4247         if (!this->emitGetPtrField(RF->Offset, E))
4248           return false;
4249         if (!this->visitAPValueInitializer(F, E))
4250           return false;
4251         if (!this->emitPopPtr(E))
4252           return false;
4253       } else {
4254         assert(false && "I don't think this should be possible");
4255       }
4256     }
4257     return true;
4258   } else if (Val.isUnion()) {
4259     const FieldDecl *UnionField = Val.getUnionField();
4260     const Record *R = this->getRecord(UnionField->getParent());
4261     assert(R);
4262     const APValue &F = Val.getUnionValue();
4263     const Record::Field *RF = R->getField(UnionField);
4264     PrimType T = classifyPrim(RF->Decl->getType());
4265     if (!this->visitAPValue(F, T, E))
4266       return false;
4267     return this->emitInitField(T, RF->Offset, E);
4268   }
4269   // TODO: Other types.
4270 
4271   return false;
4272 }
4273 
4274 template <class Emitter>
4275 bool Compiler<Emitter>::VisitBuiltinCallExpr(const CallExpr *E,
4276                                              unsigned BuiltinID) {
4277   const Function *Func = getFunction(E->getDirectCallee());
4278   if (!Func)
4279     return false;
4280 
4281   // For these, we're expected to ultimately return an APValue pointing
4282   // to the CallExpr. This is needed to get the correct codegen.
4283   if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4284       BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString ||
4285       BuiltinID == Builtin::BI__builtin_ptrauth_sign_constant ||
4286       BuiltinID == Builtin::BI__builtin_function_start) {
4287     if (std::optional<unsigned> GlobalOffset = P.getOrCreateDummy(E)) {
4288       if (!this->emitGetPtrGlobal(*GlobalOffset, E))
4289         return false;
4290 
4291       if (PrimType PT = classifyPrim(E); PT != PT_Ptr && isPtrType(PT))
4292         return this->emitDecayPtr(PT_Ptr, PT, E);
4293       return true;
4294     }
4295     return false;
4296   }
4297 
4298   QualType ReturnType = E->getType();
4299   std::optional<PrimType> ReturnT = classify(E);
4300 
4301   // Non-primitive return type. Prepare storage.
4302   if (!Initializing && !ReturnT && !ReturnType->isVoidType()) {
4303     std::optional<unsigned> LocalIndex = allocateLocal(E);
4304     if (!LocalIndex)
4305       return false;
4306     if (!this->emitGetPtrLocal(*LocalIndex, E))
4307       return false;
4308   }
4309 
4310   if (!Func->isUnevaluatedBuiltin()) {
4311     // Put arguments on the stack.
4312     for (const auto *Arg : E->arguments()) {
4313       if (!this->visit(Arg))
4314         return false;
4315     }
4316   }
4317 
4318   if (!this->emitCallBI(Func, E, BuiltinID, E))
4319     return false;
4320 
4321   if (DiscardResult && !ReturnType->isVoidType()) {
4322     assert(ReturnT);
4323     return this->emitPop(*ReturnT, E);
4324   }
4325 
4326   return true;
4327 }
4328 
4329 template <class Emitter>
4330 bool Compiler<Emitter>::VisitCallExpr(const CallExpr *E) {
4331   if (unsigned BuiltinID = E->getBuiltinCallee())
4332     return VisitBuiltinCallExpr(E, BuiltinID);
4333 
4334   const FunctionDecl *FuncDecl = E->getDirectCallee();
4335   // Calls to replaceable operator new/operator delete.
4336   if (FuncDecl && FuncDecl->isReplaceableGlobalAllocationFunction()) {
4337     if (FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_New ||
4338         FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
4339       return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_new);
4340     } else {
4341       assert(FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_Delete);
4342       return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_delete);
4343     }
4344   }
4345 
4346   QualType ReturnType = E->getCallReturnType(Ctx.getASTContext());
4347   std::optional<PrimType> T = classify(ReturnType);
4348   bool HasRVO = !ReturnType->isVoidType() && !T;
4349 
4350   if (HasRVO) {
4351     if (DiscardResult) {
4352       // If we need to discard the return value but the function returns its
4353       // value via an RVO pointer, we need to create one such pointer just
4354       // for this call.
4355       if (std::optional<unsigned> LocalIndex = allocateLocal(E)) {
4356         if (!this->emitGetPtrLocal(*LocalIndex, E))
4357           return false;
4358       }
4359     } else {
4360       // We need the result. Prepare a pointer to return or
4361       // dup the current one.
4362       if (!Initializing) {
4363         if (std::optional<unsigned> LocalIndex = allocateLocal(E)) {
4364           if (!this->emitGetPtrLocal(*LocalIndex, E))
4365             return false;
4366         }
4367       }
4368       if (!this->emitDupPtr(E))
4369         return false;
4370     }
4371   }
4372 
4373   SmallVector<const Expr *, 8> Args(
4374       llvm::ArrayRef(E->getArgs(), E->getNumArgs()));
4375 
4376   bool IsAssignmentOperatorCall = false;
4377   if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
4378       OCE && OCE->isAssignmentOp()) {
4379     // Just like with regular assignments, we need to special-case assignment
4380     // operators here and evaluate the RHS (the second arg) before the LHS (the
4381     // first arg. We fix this by using a Flip op later.
4382     assert(Args.size() == 2);
4383     IsAssignmentOperatorCall = true;
4384     std::reverse(Args.begin(), Args.end());
4385   }
4386   // Calling a static operator will still
4387   // pass the instance, but we don't need it.
4388   // Discard it here.
4389   if (isa<CXXOperatorCallExpr>(E)) {
4390     if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl);
4391         MD && MD->isStatic()) {
4392       if (!this->discard(E->getArg(0)))
4393         return false;
4394       // Drop first arg.
4395       Args.erase(Args.begin());
4396     }
4397   }
4398 
4399   std::optional<unsigned> CalleeOffset;
4400   // Add the (optional, implicit) This pointer.
4401   if (const auto *MC = dyn_cast<CXXMemberCallExpr>(E)) {
4402     if (!FuncDecl && classifyPrim(E->getCallee()) == PT_MemberPtr) {
4403       // If we end up creating a CallPtr op for this, we need the base of the
4404       // member pointer as the instance pointer, and later extract the function
4405       // decl as the function pointer.
4406       const Expr *Callee = E->getCallee();
4407       CalleeOffset =
4408           this->allocateLocalPrimitive(Callee, PT_MemberPtr, true, false);
4409       if (!this->visit(Callee))
4410         return false;
4411       if (!this->emitSetLocal(PT_MemberPtr, *CalleeOffset, E))
4412         return false;
4413       if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
4414         return false;
4415       if (!this->emitGetMemberPtrBase(E))
4416         return false;
4417     } else if (!this->visit(MC->getImplicitObjectArgument())) {
4418       return false;
4419     }
4420   } else if (!FuncDecl) {
4421     const Expr *Callee = E->getCallee();
4422     CalleeOffset = this->allocateLocalPrimitive(Callee, PT_FnPtr, true, false);
4423     if (!this->visit(Callee))
4424       return false;
4425     if (!this->emitSetLocal(PT_FnPtr, *CalleeOffset, E))
4426       return false;
4427   }
4428 
4429   llvm::BitVector NonNullArgs = collectNonNullArgs(FuncDecl, Args);
4430   // Put arguments on the stack.
4431   unsigned ArgIndex = 0;
4432   for (const auto *Arg : Args) {
4433     if (!this->visit(Arg))
4434       return false;
4435 
4436     // If we know the callee already, check the known parametrs for nullability.
4437     if (FuncDecl && NonNullArgs[ArgIndex]) {
4438       PrimType ArgT = classify(Arg).value_or(PT_Ptr);
4439       if (ArgT == PT_Ptr || ArgT == PT_FnPtr) {
4440         if (!this->emitCheckNonNullArg(ArgT, Arg))
4441           return false;
4442       }
4443     }
4444     ++ArgIndex;
4445   }
4446 
4447   // Undo the argument reversal we did earlier.
4448   if (IsAssignmentOperatorCall) {
4449     assert(Args.size() == 2);
4450     PrimType Arg1T = classify(Args[0]).value_or(PT_Ptr);
4451     PrimType Arg2T = classify(Args[1]).value_or(PT_Ptr);
4452     if (!this->emitFlip(Arg2T, Arg1T, E))
4453       return false;
4454   }
4455 
4456   if (FuncDecl) {
4457     const Function *Func = getFunction(FuncDecl);
4458     if (!Func)
4459       return false;
4460     assert(HasRVO == Func->hasRVO());
4461 
4462     bool HasQualifier = false;
4463     if (const auto *ME = dyn_cast<MemberExpr>(E->getCallee()))
4464       HasQualifier = ME->hasQualifier();
4465 
4466     bool IsVirtual = false;
4467     if (const auto *MD = dyn_cast<CXXMethodDecl>(FuncDecl))
4468       IsVirtual = MD->isVirtual();
4469 
4470     // In any case call the function. The return value will end up on the stack
4471     // and if the function has RVO, we already have the pointer on the stack to
4472     // write the result into.
4473     if (IsVirtual && !HasQualifier) {
4474       uint32_t VarArgSize = 0;
4475       unsigned NumParams =
4476           Func->getNumWrittenParams() + isa<CXXOperatorCallExpr>(E);
4477       for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
4478         VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
4479 
4480       if (!this->emitCallVirt(Func, VarArgSize, E))
4481         return false;
4482     } else if (Func->isVariadic()) {
4483       uint32_t VarArgSize = 0;
4484       unsigned NumParams =
4485           Func->getNumWrittenParams() + isa<CXXOperatorCallExpr>(E);
4486       for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
4487         VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
4488       if (!this->emitCallVar(Func, VarArgSize, E))
4489         return false;
4490     } else {
4491       if (!this->emitCall(Func, 0, E))
4492         return false;
4493     }
4494   } else {
4495     // Indirect call. Visit the callee, which will leave a FunctionPointer on
4496     // the stack. Cleanup of the returned value if necessary will be done after
4497     // the function call completed.
4498 
4499     // Sum the size of all args from the call expr.
4500     uint32_t ArgSize = 0;
4501     for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
4502       ArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
4503 
4504     // Get the callee, either from a member pointer or function pointer saved in
4505     // CalleeOffset.
4506     if (isa<CXXMemberCallExpr>(E) && CalleeOffset) {
4507       if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
4508         return false;
4509       if (!this->emitGetMemberPtrDecl(E))
4510         return false;
4511     } else {
4512       if (!this->emitGetLocal(PT_FnPtr, *CalleeOffset, E))
4513         return false;
4514     }
4515     if (!this->emitCallPtr(ArgSize, E, E))
4516       return false;
4517   }
4518 
4519   // Cleanup for discarded return values.
4520   if (DiscardResult && !ReturnType->isVoidType() && T)
4521     return this->emitPop(*T, E);
4522 
4523   return true;
4524 }
4525 
4526 template <class Emitter>
4527 bool Compiler<Emitter>::VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4528   SourceLocScope<Emitter> SLS(this, E);
4529 
4530   return this->delegate(E->getExpr());
4531 }
4532 
4533 template <class Emitter>
4534 bool Compiler<Emitter>::VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4535   SourceLocScope<Emitter> SLS(this, E);
4536 
4537   const Expr *SubExpr = E->getExpr();
4538   if (std::optional<PrimType> T = classify(E->getExpr()))
4539     return this->visit(SubExpr);
4540 
4541   assert(Initializing);
4542   return this->visitInitializer(SubExpr);
4543 }
4544 
4545 template <class Emitter>
4546 bool Compiler<Emitter>::VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
4547   if (DiscardResult)
4548     return true;
4549 
4550   return this->emitConstBool(E->getValue(), E);
4551 }
4552 
4553 template <class Emitter>
4554 bool Compiler<Emitter>::VisitCXXNullPtrLiteralExpr(
4555     const CXXNullPtrLiteralExpr *E) {
4556   if (DiscardResult)
4557     return true;
4558 
4559   return this->emitNullPtr(nullptr, E);
4560 }
4561 
4562 template <class Emitter>
4563 bool Compiler<Emitter>::VisitGNUNullExpr(const GNUNullExpr *E) {
4564   if (DiscardResult)
4565     return true;
4566 
4567   assert(E->getType()->isIntegerType());
4568 
4569   PrimType T = classifyPrim(E->getType());
4570   return this->emitZero(T, E);
4571 }
4572 
4573 template <class Emitter>
4574 bool Compiler<Emitter>::VisitCXXThisExpr(const CXXThisExpr *E) {
4575   if (DiscardResult)
4576     return true;
4577 
4578   if (this->LambdaThisCapture.Offset > 0) {
4579     if (this->LambdaThisCapture.IsPtr)
4580       return this->emitGetThisFieldPtr(this->LambdaThisCapture.Offset, E);
4581     return this->emitGetPtrThisField(this->LambdaThisCapture.Offset, E);
4582   }
4583 
4584   // In some circumstances, the 'this' pointer does not actually refer to the
4585   // instance pointer of the current function frame, but e.g. to the declaration
4586   // currently being initialized. Here we emit the necessary instruction(s) for
4587   // this scenario.
4588   if (!InitStackActive || !E->isImplicit())
4589     return this->emitThis(E);
4590 
4591   if (InitStackActive && !InitStack.empty()) {
4592     unsigned StartIndex = 0;
4593     for (StartIndex = InitStack.size() - 1; StartIndex > 0; --StartIndex) {
4594       if (InitStack[StartIndex].Kind != InitLink::K_Field &&
4595           InitStack[StartIndex].Kind != InitLink::K_Elem)
4596         break;
4597     }
4598 
4599     for (unsigned I = StartIndex, N = InitStack.size(); I != N; ++I) {
4600       if (!InitStack[I].template emit<Emitter>(this, E))
4601         return false;
4602     }
4603     return true;
4604   }
4605   return this->emitThis(E);
4606 }
4607 
4608 template <class Emitter> bool Compiler<Emitter>::visitStmt(const Stmt *S) {
4609   switch (S->getStmtClass()) {
4610   case Stmt::CompoundStmtClass:
4611     return visitCompoundStmt(cast<CompoundStmt>(S));
4612   case Stmt::DeclStmtClass:
4613     return visitDeclStmt(cast<DeclStmt>(S));
4614   case Stmt::ReturnStmtClass:
4615     return visitReturnStmt(cast<ReturnStmt>(S));
4616   case Stmt::IfStmtClass:
4617     return visitIfStmt(cast<IfStmt>(S));
4618   case Stmt::WhileStmtClass:
4619     return visitWhileStmt(cast<WhileStmt>(S));
4620   case Stmt::DoStmtClass:
4621     return visitDoStmt(cast<DoStmt>(S));
4622   case Stmt::ForStmtClass:
4623     return visitForStmt(cast<ForStmt>(S));
4624   case Stmt::CXXForRangeStmtClass:
4625     return visitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
4626   case Stmt::BreakStmtClass:
4627     return visitBreakStmt(cast<BreakStmt>(S));
4628   case Stmt::ContinueStmtClass:
4629     return visitContinueStmt(cast<ContinueStmt>(S));
4630   case Stmt::SwitchStmtClass:
4631     return visitSwitchStmt(cast<SwitchStmt>(S));
4632   case Stmt::CaseStmtClass:
4633     return visitCaseStmt(cast<CaseStmt>(S));
4634   case Stmt::DefaultStmtClass:
4635     return visitDefaultStmt(cast<DefaultStmt>(S));
4636   case Stmt::AttributedStmtClass:
4637     return visitAttributedStmt(cast<AttributedStmt>(S));
4638   case Stmt::CXXTryStmtClass:
4639     return visitCXXTryStmt(cast<CXXTryStmt>(S));
4640   case Stmt::NullStmtClass:
4641     return true;
4642   // Always invalid statements.
4643   case Stmt::GCCAsmStmtClass:
4644   case Stmt::MSAsmStmtClass:
4645   case Stmt::GotoStmtClass:
4646     return this->emitInvalid(S);
4647   case Stmt::LabelStmtClass:
4648     return this->visitStmt(cast<LabelStmt>(S)->getSubStmt());
4649   default: {
4650     if (const auto *E = dyn_cast<Expr>(S))
4651       return this->discard(E);
4652     return false;
4653   }
4654   }
4655 }
4656 
4657 template <class Emitter>
4658 bool Compiler<Emitter>::visitCompoundStmt(const CompoundStmt *S) {
4659   BlockScope<Emitter> Scope(this);
4660   for (const auto *InnerStmt : S->body())
4661     if (!visitStmt(InnerStmt))
4662       return false;
4663   return Scope.destroyLocals();
4664 }
4665 
4666 template <class Emitter>
4667 bool Compiler<Emitter>::visitDeclStmt(const DeclStmt *DS) {
4668   for (const auto *D : DS->decls()) {
4669     if (isa<StaticAssertDecl, TagDecl, TypedefNameDecl, UsingEnumDecl,
4670             FunctionDecl>(D))
4671       continue;
4672 
4673     const auto *VD = dyn_cast<VarDecl>(D);
4674     if (!VD)
4675       return false;
4676     if (!this->visitVarDecl(VD))
4677       return false;
4678   }
4679 
4680   return true;
4681 }
4682 
4683 template <class Emitter>
4684 bool Compiler<Emitter>::visitReturnStmt(const ReturnStmt *RS) {
4685   if (this->InStmtExpr)
4686     return this->emitUnsupported(RS);
4687 
4688   if (const Expr *RE = RS->getRetValue()) {
4689     LocalScope<Emitter> RetScope(this);
4690     if (ReturnType) {
4691       // Primitive types are simply returned.
4692       if (!this->visit(RE))
4693         return false;
4694       this->emitCleanup();
4695       return this->emitRet(*ReturnType, RS);
4696     } else if (RE->getType()->isVoidType()) {
4697       if (!this->visit(RE))
4698         return false;
4699     } else {
4700       // RVO - construct the value in the return location.
4701       if (!this->emitRVOPtr(RE))
4702         return false;
4703       if (!this->visitInitializer(RE))
4704         return false;
4705       if (!this->emitPopPtr(RE))
4706         return false;
4707 
4708       this->emitCleanup();
4709       return this->emitRetVoid(RS);
4710     }
4711   }
4712 
4713   // Void return.
4714   this->emitCleanup();
4715   return this->emitRetVoid(RS);
4716 }
4717 
4718 template <class Emitter> bool Compiler<Emitter>::visitIfStmt(const IfStmt *IS) {
4719   if (auto *CondInit = IS->getInit())
4720     if (!visitStmt(CondInit))
4721       return false;
4722 
4723   if (const DeclStmt *CondDecl = IS->getConditionVariableDeclStmt())
4724     if (!visitDeclStmt(CondDecl))
4725       return false;
4726 
4727   // Compile condition.
4728   if (IS->isNonNegatedConsteval()) {
4729     if (!this->emitIsConstantContext(IS))
4730       return false;
4731   } else if (IS->isNegatedConsteval()) {
4732     if (!this->emitIsConstantContext(IS))
4733       return false;
4734     if (!this->emitInv(IS))
4735       return false;
4736   } else {
4737     if (!this->visitBool(IS->getCond()))
4738       return false;
4739   }
4740 
4741   if (const Stmt *Else = IS->getElse()) {
4742     LabelTy LabelElse = this->getLabel();
4743     LabelTy LabelEnd = this->getLabel();
4744     if (!this->jumpFalse(LabelElse))
4745       return false;
4746     if (!visitStmt(IS->getThen()))
4747       return false;
4748     if (!this->jump(LabelEnd))
4749       return false;
4750     this->emitLabel(LabelElse);
4751     if (!visitStmt(Else))
4752       return false;
4753     this->emitLabel(LabelEnd);
4754   } else {
4755     LabelTy LabelEnd = this->getLabel();
4756     if (!this->jumpFalse(LabelEnd))
4757       return false;
4758     if (!visitStmt(IS->getThen()))
4759       return false;
4760     this->emitLabel(LabelEnd);
4761   }
4762 
4763   return true;
4764 }
4765 
4766 template <class Emitter>
4767 bool Compiler<Emitter>::visitWhileStmt(const WhileStmt *S) {
4768   const Expr *Cond = S->getCond();
4769   const Stmt *Body = S->getBody();
4770 
4771   LabelTy CondLabel = this->getLabel(); // Label before the condition.
4772   LabelTy EndLabel = this->getLabel();  // Label after the loop.
4773   LoopScope<Emitter> LS(this, EndLabel, CondLabel);
4774 
4775   this->fallthrough(CondLabel);
4776   this->emitLabel(CondLabel);
4777 
4778   {
4779     LocalScope<Emitter> CondScope(this);
4780     if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
4781       if (!visitDeclStmt(CondDecl))
4782         return false;
4783 
4784     if (!this->visitBool(Cond))
4785       return false;
4786     if (!this->jumpFalse(EndLabel))
4787       return false;
4788 
4789     if (!this->visitStmt(Body))
4790       return false;
4791 
4792     if (!CondScope.destroyLocals())
4793       return false;
4794   }
4795   if (!this->jump(CondLabel))
4796     return false;
4797   this->fallthrough(EndLabel);
4798   this->emitLabel(EndLabel);
4799 
4800   return true;
4801 }
4802 
4803 template <class Emitter> bool Compiler<Emitter>::visitDoStmt(const DoStmt *S) {
4804   const Expr *Cond = S->getCond();
4805   const Stmt *Body = S->getBody();
4806 
4807   LabelTy StartLabel = this->getLabel();
4808   LabelTy EndLabel = this->getLabel();
4809   LabelTy CondLabel = this->getLabel();
4810   LoopScope<Emitter> LS(this, EndLabel, CondLabel);
4811 
4812   this->fallthrough(StartLabel);
4813   this->emitLabel(StartLabel);
4814 
4815   {
4816     LocalScope<Emitter> CondScope(this);
4817     if (!this->visitStmt(Body))
4818       return false;
4819     this->fallthrough(CondLabel);
4820     this->emitLabel(CondLabel);
4821     if (!this->visitBool(Cond))
4822       return false;
4823 
4824     if (!CondScope.destroyLocals())
4825       return false;
4826   }
4827   if (!this->jumpTrue(StartLabel))
4828     return false;
4829 
4830   this->fallthrough(EndLabel);
4831   this->emitLabel(EndLabel);
4832   return true;
4833 }
4834 
4835 template <class Emitter>
4836 bool Compiler<Emitter>::visitForStmt(const ForStmt *S) {
4837   // for (Init; Cond; Inc) { Body }
4838   const Stmt *Init = S->getInit();
4839   const Expr *Cond = S->getCond();
4840   const Expr *Inc = S->getInc();
4841   const Stmt *Body = S->getBody();
4842 
4843   LabelTy EndLabel = this->getLabel();
4844   LabelTy CondLabel = this->getLabel();
4845   LabelTy IncLabel = this->getLabel();
4846   LoopScope<Emitter> LS(this, EndLabel, IncLabel);
4847 
4848   if (Init && !this->visitStmt(Init))
4849     return false;
4850 
4851   this->fallthrough(CondLabel);
4852   this->emitLabel(CondLabel);
4853 
4854   {
4855     LocalScope<Emitter> CondScope(this);
4856     if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
4857       if (!visitDeclStmt(CondDecl))
4858         return false;
4859 
4860     if (Cond) {
4861       if (!this->visitBool(Cond))
4862         return false;
4863       if (!this->jumpFalse(EndLabel))
4864         return false;
4865     }
4866 
4867     if (Body && !this->visitStmt(Body))
4868       return false;
4869 
4870     this->fallthrough(IncLabel);
4871     this->emitLabel(IncLabel);
4872     if (Inc && !this->discard(Inc))
4873       return false;
4874 
4875     if (!CondScope.destroyLocals())
4876       return false;
4877   }
4878   if (!this->jump(CondLabel))
4879     return false;
4880 
4881   this->fallthrough(EndLabel);
4882   this->emitLabel(EndLabel);
4883   return true;
4884 }
4885 
4886 template <class Emitter>
4887 bool Compiler<Emitter>::visitCXXForRangeStmt(const CXXForRangeStmt *S) {
4888   const Stmt *Init = S->getInit();
4889   const Expr *Cond = S->getCond();
4890   const Expr *Inc = S->getInc();
4891   const Stmt *Body = S->getBody();
4892   const Stmt *BeginStmt = S->getBeginStmt();
4893   const Stmt *RangeStmt = S->getRangeStmt();
4894   const Stmt *EndStmt = S->getEndStmt();
4895   const VarDecl *LoopVar = S->getLoopVariable();
4896 
4897   LabelTy EndLabel = this->getLabel();
4898   LabelTy CondLabel = this->getLabel();
4899   LabelTy IncLabel = this->getLabel();
4900   LoopScope<Emitter> LS(this, EndLabel, IncLabel);
4901 
4902   // Emit declarations needed in the loop.
4903   if (Init && !this->visitStmt(Init))
4904     return false;
4905   if (!this->visitStmt(RangeStmt))
4906     return false;
4907   if (!this->visitStmt(BeginStmt))
4908     return false;
4909   if (!this->visitStmt(EndStmt))
4910     return false;
4911 
4912   // Now the condition as well as the loop variable assignment.
4913   this->fallthrough(CondLabel);
4914   this->emitLabel(CondLabel);
4915   if (!this->visitBool(Cond))
4916     return false;
4917   if (!this->jumpFalse(EndLabel))
4918     return false;
4919 
4920   if (!this->visitVarDecl(LoopVar))
4921     return false;
4922 
4923   // Body.
4924   {
4925     if (!this->visitStmt(Body))
4926       return false;
4927 
4928     this->fallthrough(IncLabel);
4929     this->emitLabel(IncLabel);
4930     if (!this->discard(Inc))
4931       return false;
4932   }
4933 
4934   if (!this->jump(CondLabel))
4935     return false;
4936 
4937   this->fallthrough(EndLabel);
4938   this->emitLabel(EndLabel);
4939   return true;
4940 }
4941 
4942 template <class Emitter>
4943 bool Compiler<Emitter>::visitBreakStmt(const BreakStmt *S) {
4944   if (!BreakLabel)
4945     return false;
4946 
4947   for (VariableScope<Emitter> *C = VarScope; C != BreakVarScope;
4948        C = C->getParent())
4949     C->emitDestruction();
4950   return this->jump(*BreakLabel);
4951 }
4952 
4953 template <class Emitter>
4954 bool Compiler<Emitter>::visitContinueStmt(const ContinueStmt *S) {
4955   if (!ContinueLabel)
4956     return false;
4957 
4958   for (VariableScope<Emitter> *C = VarScope;
4959        C && C->getParent() != ContinueVarScope; C = C->getParent())
4960     C->emitDestruction();
4961   return this->jump(*ContinueLabel);
4962 }
4963 
4964 template <class Emitter>
4965 bool Compiler<Emitter>::visitSwitchStmt(const SwitchStmt *S) {
4966   const Expr *Cond = S->getCond();
4967   PrimType CondT = this->classifyPrim(Cond->getType());
4968   LocalScope<Emitter> LS(this);
4969 
4970   LabelTy EndLabel = this->getLabel();
4971   OptLabelTy DefaultLabel = std::nullopt;
4972   unsigned CondVar = this->allocateLocalPrimitive(Cond, CondT, true, false);
4973 
4974   if (const auto *CondInit = S->getInit())
4975     if (!visitStmt(CondInit))
4976       return false;
4977 
4978   if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
4979     if (!visitDeclStmt(CondDecl))
4980       return false;
4981 
4982   // Initialize condition variable.
4983   if (!this->visit(Cond))
4984     return false;
4985   if (!this->emitSetLocal(CondT, CondVar, S))
4986     return false;
4987 
4988   CaseMap CaseLabels;
4989   // Create labels and comparison ops for all case statements.
4990   for (const SwitchCase *SC = S->getSwitchCaseList(); SC;
4991        SC = SC->getNextSwitchCase()) {
4992     if (const auto *CS = dyn_cast<CaseStmt>(SC)) {
4993       // FIXME: Implement ranges.
4994       if (CS->caseStmtIsGNURange())
4995         return false;
4996       CaseLabels[SC] = this->getLabel();
4997 
4998       const Expr *Value = CS->getLHS();
4999       PrimType ValueT = this->classifyPrim(Value->getType());
5000 
5001       // Compare the case statement's value to the switch condition.
5002       if (!this->emitGetLocal(CondT, CondVar, CS))
5003         return false;
5004       if (!this->visit(Value))
5005         return false;
5006 
5007       // Compare and jump to the case label.
5008       if (!this->emitEQ(ValueT, S))
5009         return false;
5010       if (!this->jumpTrue(CaseLabels[CS]))
5011         return false;
5012     } else {
5013       assert(!DefaultLabel);
5014       DefaultLabel = this->getLabel();
5015     }
5016   }
5017 
5018   // If none of the conditions above were true, fall through to the default
5019   // statement or jump after the switch statement.
5020   if (DefaultLabel) {
5021     if (!this->jump(*DefaultLabel))
5022       return false;
5023   } else {
5024     if (!this->jump(EndLabel))
5025       return false;
5026   }
5027 
5028   SwitchScope<Emitter> SS(this, std::move(CaseLabels), EndLabel, DefaultLabel);
5029   if (!this->visitStmt(S->getBody()))
5030     return false;
5031   this->emitLabel(EndLabel);
5032 
5033   return LS.destroyLocals();
5034 }
5035 
5036 template <class Emitter>
5037 bool Compiler<Emitter>::visitCaseStmt(const CaseStmt *S) {
5038   this->emitLabel(CaseLabels[S]);
5039   return this->visitStmt(S->getSubStmt());
5040 }
5041 
5042 template <class Emitter>
5043 bool Compiler<Emitter>::visitDefaultStmt(const DefaultStmt *S) {
5044   this->emitLabel(*DefaultLabel);
5045   return this->visitStmt(S->getSubStmt());
5046 }
5047 
5048 template <class Emitter>
5049 bool Compiler<Emitter>::visitAttributedStmt(const AttributedStmt *S) {
5050   if (this->Ctx.getLangOpts().CXXAssumptions &&
5051       !this->Ctx.getLangOpts().MSVCCompat) {
5052     for (const Attr *A : S->getAttrs()) {
5053       auto *AA = dyn_cast<CXXAssumeAttr>(A);
5054       if (!AA)
5055         continue;
5056 
5057       assert(isa<NullStmt>(S->getSubStmt()));
5058 
5059       const Expr *Assumption = AA->getAssumption();
5060       if (Assumption->isValueDependent())
5061         return false;
5062 
5063       if (Assumption->HasSideEffects(this->Ctx.getASTContext()))
5064         continue;
5065 
5066       // Evaluate assumption.
5067       if (!this->visitBool(Assumption))
5068         return false;
5069 
5070       if (!this->emitAssume(Assumption))
5071         return false;
5072     }
5073   }
5074 
5075   // Ignore other attributes.
5076   return this->visitStmt(S->getSubStmt());
5077 }
5078 
5079 template <class Emitter>
5080 bool Compiler<Emitter>::visitCXXTryStmt(const CXXTryStmt *S) {
5081   // Ignore all handlers.
5082   return this->visitStmt(S->getTryBlock());
5083 }
5084 
5085 template <class Emitter>
5086 bool Compiler<Emitter>::emitLambdaStaticInvokerBody(const CXXMethodDecl *MD) {
5087   assert(MD->isLambdaStaticInvoker());
5088   assert(MD->hasBody());
5089   assert(cast<CompoundStmt>(MD->getBody())->body_empty());
5090 
5091   const CXXRecordDecl *ClosureClass = MD->getParent();
5092   const CXXMethodDecl *LambdaCallOp = ClosureClass->getLambdaCallOperator();
5093   assert(ClosureClass->captures_begin() == ClosureClass->captures_end());
5094   const Function *Func = this->getFunction(LambdaCallOp);
5095   if (!Func)
5096     return false;
5097   assert(Func->hasThisPointer());
5098   assert(Func->getNumParams() == (MD->getNumParams() + 1 + Func->hasRVO()));
5099 
5100   if (Func->hasRVO()) {
5101     if (!this->emitRVOPtr(MD))
5102       return false;
5103   }
5104 
5105   // The lambda call operator needs an instance pointer, but we don't have
5106   // one here, and we don't need one either because the lambda cannot have
5107   // any captures, as verified above. Emit a null pointer. This is then
5108   // special-cased when interpreting to not emit any misleading diagnostics.
5109   if (!this->emitNullPtr(nullptr, MD))
5110     return false;
5111 
5112   // Forward all arguments from the static invoker to the lambda call operator.
5113   for (const ParmVarDecl *PVD : MD->parameters()) {
5114     auto It = this->Params.find(PVD);
5115     assert(It != this->Params.end());
5116 
5117     // We do the lvalue-to-rvalue conversion manually here, so no need
5118     // to care about references.
5119     PrimType ParamType = this->classify(PVD->getType()).value_or(PT_Ptr);
5120     if (!this->emitGetParam(ParamType, It->second.Offset, MD))
5121       return false;
5122   }
5123 
5124   if (!this->emitCall(Func, 0, LambdaCallOp))
5125     return false;
5126 
5127   this->emitCleanup();
5128   if (ReturnType)
5129     return this->emitRet(*ReturnType, MD);
5130 
5131   // Nothing to do, since we emitted the RVO pointer above.
5132   return this->emitRetVoid(MD);
5133 }
5134 
5135 template <class Emitter>
5136 bool Compiler<Emitter>::checkLiteralType(const Expr *E) {
5137   if (Ctx.getLangOpts().CPlusPlus23)
5138     return true;
5139 
5140   if (!E->isPRValue() || E->getType()->isLiteralType(Ctx.getASTContext()))
5141     return true;
5142 
5143   return this->emitCheckLiteralType(E->getType().getTypePtr(), E);
5144 }
5145 
5146 template <class Emitter>
5147 bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
5148   assert(!ReturnType);
5149 
5150   auto emitFieldInitializer = [&](const Record::Field *F, unsigned FieldOffset,
5151                                   const Expr *InitExpr) -> bool {
5152     // We don't know what to do with these, so just return false.
5153     if (InitExpr->getType().isNull())
5154       return false;
5155 
5156     if (std::optional<PrimType> T = this->classify(InitExpr)) {
5157       if (!this->visit(InitExpr))
5158         return false;
5159 
5160       if (F->isBitField())
5161         return this->emitInitThisBitField(*T, F, FieldOffset, InitExpr);
5162       return this->emitInitThisField(*T, FieldOffset, InitExpr);
5163     }
5164     // Non-primitive case. Get a pointer to the field-to-initialize
5165     // on the stack and call visitInitialzer() for it.
5166     InitLinkScope<Emitter> FieldScope(this, InitLink::Field(F->Offset));
5167     if (!this->emitGetPtrThisField(FieldOffset, InitExpr))
5168       return false;
5169 
5170     if (!this->visitInitializer(InitExpr))
5171       return false;
5172 
5173     return this->emitFinishInitPop(InitExpr);
5174   };
5175 
5176   const RecordDecl *RD = Ctor->getParent();
5177   const Record *R = this->getRecord(RD);
5178   if (!R)
5179     return false;
5180 
5181   if (R->isUnion() && Ctor->isCopyOrMoveConstructor()) {
5182     // union copy and move ctors are special.
5183     assert(cast<CompoundStmt>(Ctor->getBody())->body_empty());
5184     if (!this->emitThis(Ctor))
5185       return false;
5186 
5187     auto PVD = Ctor->getParamDecl(0);
5188     ParamOffset PO = this->Params[PVD]; // Must exist.
5189 
5190     if (!this->emitGetParam(PT_Ptr, PO.Offset, Ctor))
5191       return false;
5192 
5193     return this->emitMemcpy(Ctor) && this->emitPopPtr(Ctor) &&
5194            this->emitRetVoid(Ctor);
5195   }
5196 
5197   InitLinkScope<Emitter> InitScope(this, InitLink::This());
5198   for (const auto *Init : Ctor->inits()) {
5199     // Scope needed for the initializers.
5200     BlockScope<Emitter> Scope(this);
5201 
5202     const Expr *InitExpr = Init->getInit();
5203     if (const FieldDecl *Member = Init->getMember()) {
5204       const Record::Field *F = R->getField(Member);
5205 
5206       if (!emitFieldInitializer(F, F->Offset, InitExpr))
5207         return false;
5208     } else if (const Type *Base = Init->getBaseClass()) {
5209       const auto *BaseDecl = Base->getAsCXXRecordDecl();
5210       assert(BaseDecl);
5211 
5212       if (Init->isBaseVirtual()) {
5213         assert(R->getVirtualBase(BaseDecl));
5214         if (!this->emitGetPtrThisVirtBase(BaseDecl, InitExpr))
5215           return false;
5216 
5217       } else {
5218         // Base class initializer.
5219         // Get This Base and call initializer on it.
5220         const Record::Base *B = R->getBase(BaseDecl);
5221         assert(B);
5222         if (!this->emitGetPtrThisBase(B->Offset, InitExpr))
5223           return false;
5224       }
5225 
5226       if (!this->visitInitializer(InitExpr))
5227         return false;
5228       if (!this->emitFinishInitPop(InitExpr))
5229         return false;
5230     } else if (const IndirectFieldDecl *IFD = Init->getIndirectMember()) {
5231       assert(IFD->getChainingSize() >= 2);
5232 
5233       unsigned NestedFieldOffset = 0;
5234       const Record::Field *NestedField = nullptr;
5235       for (const NamedDecl *ND : IFD->chain()) {
5236         const auto *FD = cast<FieldDecl>(ND);
5237         const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
5238         assert(FieldRecord);
5239 
5240         NestedField = FieldRecord->getField(FD);
5241         assert(NestedField);
5242 
5243         NestedFieldOffset += NestedField->Offset;
5244       }
5245       assert(NestedField);
5246 
5247       if (!emitFieldInitializer(NestedField, NestedFieldOffset, InitExpr))
5248         return false;
5249     } else {
5250       assert(Init->isDelegatingInitializer());
5251       if (!this->emitThis(InitExpr))
5252         return false;
5253       if (!this->visitInitializer(Init->getInit()))
5254         return false;
5255       if (!this->emitPopPtr(InitExpr))
5256         return false;
5257     }
5258 
5259     if (!Scope.destroyLocals())
5260       return false;
5261   }
5262 
5263   if (const auto *Body = Ctor->getBody())
5264     if (!visitStmt(Body))
5265       return false;
5266 
5267   return this->emitRetVoid(SourceInfo{});
5268 }
5269 
5270 template <class Emitter>
5271 bool Compiler<Emitter>::compileDestructor(const CXXDestructorDecl *Dtor) {
5272   const RecordDecl *RD = Dtor->getParent();
5273   const Record *R = this->getRecord(RD);
5274   if (!R)
5275     return false;
5276 
5277   if (!Dtor->isTrivial() && Dtor->getBody()) {
5278     if (!this->visitStmt(Dtor->getBody()))
5279       return false;
5280   }
5281 
5282   if (!this->emitThis(Dtor))
5283     return false;
5284 
5285   assert(R);
5286   if (!R->isUnion()) {
5287     // First, destroy all fields.
5288     for (const Record::Field &Field : llvm::reverse(R->fields())) {
5289       const Descriptor *D = Field.Desc;
5290       if (!D->isPrimitive() && !D->isPrimitiveArray()) {
5291         if (!this->emitGetPtrField(Field.Offset, SourceInfo{}))
5292           return false;
5293         if (!this->emitDestruction(D))
5294           return false;
5295         if (!this->emitPopPtr(SourceInfo{}))
5296           return false;
5297       }
5298     }
5299   }
5300 
5301   for (const Record::Base &Base : llvm::reverse(R->bases())) {
5302     if (!this->emitGetPtrBase(Base.Offset, SourceInfo{}))
5303       return false;
5304     if (!this->emitRecordDestruction(Base.R))
5305       return false;
5306     if (!this->emitPopPtr(SourceInfo{}))
5307       return false;
5308   }
5309 
5310   // FIXME: Virtual bases.
5311   return this->emitPopPtr(Dtor) && this->emitRetVoid(Dtor);
5312 }
5313 
5314 template <class Emitter>
5315 bool Compiler<Emitter>::visitFunc(const FunctionDecl *F) {
5316   // Classify the return type.
5317   ReturnType = this->classify(F->getReturnType());
5318 
5319   if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(F))
5320     return this->compileConstructor(Ctor);
5321   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(F))
5322     return this->compileDestructor(Dtor);
5323 
5324   // Emit custom code if this is a lambda static invoker.
5325   if (const auto *MD = dyn_cast<CXXMethodDecl>(F);
5326       MD && MD->isLambdaStaticInvoker())
5327     return this->emitLambdaStaticInvokerBody(MD);
5328 
5329   // Regular functions.
5330   if (const auto *Body = F->getBody())
5331     if (!visitStmt(Body))
5332       return false;
5333 
5334   // Emit a guard return to protect against a code path missing one.
5335   if (F->getReturnType()->isVoidType())
5336     return this->emitRetVoid(SourceInfo{});
5337   return this->emitNoRet(SourceInfo{});
5338 }
5339 
5340 template <class Emitter>
5341 bool Compiler<Emitter>::VisitUnaryOperator(const UnaryOperator *E) {
5342   const Expr *SubExpr = E->getSubExpr();
5343   if (SubExpr->getType()->isAnyComplexType())
5344     return this->VisitComplexUnaryOperator(E);
5345   if (SubExpr->getType()->isVectorType())
5346     return this->VisitVectorUnaryOperator(E);
5347   std::optional<PrimType> T = classify(SubExpr->getType());
5348 
5349   switch (E->getOpcode()) {
5350   case UO_PostInc: { // x++
5351     if (!Ctx.getLangOpts().CPlusPlus14)
5352       return this->emitInvalid(E);
5353     if (!T)
5354       return this->emitError(E);
5355 
5356     if (!this->visit(SubExpr))
5357       return false;
5358 
5359     if (T == PT_Ptr || T == PT_FnPtr) {
5360       if (!this->emitIncPtr(E))
5361         return false;
5362 
5363       return DiscardResult ? this->emitPopPtr(E) : true;
5364     }
5365 
5366     if (T == PT_Float) {
5367       return DiscardResult ? this->emitIncfPop(getFPOptions(E), E)
5368                            : this->emitIncf(getFPOptions(E), E);
5369     }
5370 
5371     return DiscardResult ? this->emitIncPop(*T, E) : this->emitInc(*T, E);
5372   }
5373   case UO_PostDec: { // x--
5374     if (!Ctx.getLangOpts().CPlusPlus14)
5375       return this->emitInvalid(E);
5376     if (!T)
5377       return this->emitError(E);
5378 
5379     if (!this->visit(SubExpr))
5380       return false;
5381 
5382     if (T == PT_Ptr || T == PT_FnPtr) {
5383       if (!this->emitDecPtr(E))
5384         return false;
5385 
5386       return DiscardResult ? this->emitPopPtr(E) : true;
5387     }
5388 
5389     if (T == PT_Float) {
5390       return DiscardResult ? this->emitDecfPop(getFPOptions(E), E)
5391                            : this->emitDecf(getFPOptions(E), E);
5392     }
5393 
5394     return DiscardResult ? this->emitDecPop(*T, E) : this->emitDec(*T, E);
5395   }
5396   case UO_PreInc: { // ++x
5397     if (!Ctx.getLangOpts().CPlusPlus14)
5398       return this->emitInvalid(E);
5399     if (!T)
5400       return this->emitError(E);
5401 
5402     if (!this->visit(SubExpr))
5403       return false;
5404 
5405     if (T == PT_Ptr || T == PT_FnPtr) {
5406       if (!this->emitLoadPtr(E))
5407         return false;
5408       if (!this->emitConstUint8(1, E))
5409         return false;
5410       if (!this->emitAddOffsetUint8(E))
5411         return false;
5412       return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
5413     }
5414 
5415     // Post-inc and pre-inc are the same if the value is to be discarded.
5416     if (DiscardResult) {
5417       if (T == PT_Float)
5418         return this->emitIncfPop(getFPOptions(E), E);
5419       return this->emitIncPop(*T, E);
5420     }
5421 
5422     if (T == PT_Float) {
5423       const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
5424       if (!this->emitLoadFloat(E))
5425         return false;
5426       if (!this->emitConstFloat(llvm::APFloat(TargetSemantics, 1), E))
5427         return false;
5428       if (!this->emitAddf(getFPOptions(E), E))
5429         return false;
5430       if (!this->emitStoreFloat(E))
5431         return false;
5432     } else {
5433       assert(isIntegralType(*T));
5434       if (!this->emitLoad(*T, E))
5435         return false;
5436       if (!this->emitConst(1, E))
5437         return false;
5438       if (!this->emitAdd(*T, E))
5439         return false;
5440       if (!this->emitStore(*T, E))
5441         return false;
5442     }
5443     return E->isGLValue() || this->emitLoadPop(*T, E);
5444   }
5445   case UO_PreDec: { // --x
5446     if (!Ctx.getLangOpts().CPlusPlus14)
5447       return this->emitInvalid(E);
5448     if (!T)
5449       return this->emitError(E);
5450 
5451     if (!this->visit(SubExpr))
5452       return false;
5453 
5454     if (T == PT_Ptr || T == PT_FnPtr) {
5455       if (!this->emitLoadPtr(E))
5456         return false;
5457       if (!this->emitConstUint8(1, E))
5458         return false;
5459       if (!this->emitSubOffsetUint8(E))
5460         return false;
5461       return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
5462     }
5463 
5464     // Post-dec and pre-dec are the same if the value is to be discarded.
5465     if (DiscardResult) {
5466       if (T == PT_Float)
5467         return this->emitDecfPop(getFPOptions(E), E);
5468       return this->emitDecPop(*T, E);
5469     }
5470 
5471     if (T == PT_Float) {
5472       const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
5473       if (!this->emitLoadFloat(E))
5474         return false;
5475       if (!this->emitConstFloat(llvm::APFloat(TargetSemantics, 1), E))
5476         return false;
5477       if (!this->emitSubf(getFPOptions(E), E))
5478         return false;
5479       if (!this->emitStoreFloat(E))
5480         return false;
5481     } else {
5482       assert(isIntegralType(*T));
5483       if (!this->emitLoad(*T, E))
5484         return false;
5485       if (!this->emitConst(1, E))
5486         return false;
5487       if (!this->emitSub(*T, E))
5488         return false;
5489       if (!this->emitStore(*T, E))
5490         return false;
5491     }
5492     return E->isGLValue() || this->emitLoadPop(*T, E);
5493   }
5494   case UO_LNot: // !x
5495     if (!T)
5496       return this->emitError(E);
5497 
5498     if (DiscardResult)
5499       return this->discard(SubExpr);
5500 
5501     if (!this->visitBool(SubExpr))
5502       return false;
5503 
5504     if (!this->emitInv(E))
5505       return false;
5506 
5507     if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
5508       return this->emitCast(PT_Bool, ET, E);
5509     return true;
5510   case UO_Minus: // -x
5511     if (!T)
5512       return this->emitError(E);
5513 
5514     if (!this->visit(SubExpr))
5515       return false;
5516     return DiscardResult ? this->emitPop(*T, E) : this->emitNeg(*T, E);
5517   case UO_Plus: // +x
5518     if (!T)
5519       return this->emitError(E);
5520 
5521     if (!this->visit(SubExpr)) // noop
5522       return false;
5523     return DiscardResult ? this->emitPop(*T, E) : true;
5524   case UO_AddrOf: // &x
5525     if (E->getType()->isMemberPointerType()) {
5526       // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5527       // member can be formed.
5528       return this->emitGetMemberPtr(cast<DeclRefExpr>(SubExpr)->getDecl(), E);
5529     }
5530     // We should already have a pointer when we get here.
5531     return this->delegate(SubExpr);
5532   case UO_Deref: // *x
5533     if (DiscardResult)
5534       return this->discard(SubExpr);
5535     return this->visit(SubExpr);
5536   case UO_Not: // ~x
5537     if (!T)
5538       return this->emitError(E);
5539 
5540     if (!this->visit(SubExpr))
5541       return false;
5542     return DiscardResult ? this->emitPop(*T, E) : this->emitComp(*T, E);
5543   case UO_Real: // __real x
5544     assert(T);
5545     return this->delegate(SubExpr);
5546   case UO_Imag: { // __imag x
5547     assert(T);
5548     if (!this->discard(SubExpr))
5549       return false;
5550     return this->visitZeroInitializer(*T, SubExpr->getType(), SubExpr);
5551   }
5552   case UO_Extension:
5553     return this->delegate(SubExpr);
5554   case UO_Coawait:
5555     assert(false && "Unhandled opcode");
5556   }
5557 
5558   return false;
5559 }
5560 
5561 template <class Emitter>
5562 bool Compiler<Emitter>::VisitComplexUnaryOperator(const UnaryOperator *E) {
5563   const Expr *SubExpr = E->getSubExpr();
5564   assert(SubExpr->getType()->isAnyComplexType());
5565 
5566   if (DiscardResult)
5567     return this->discard(SubExpr);
5568 
5569   std::optional<PrimType> ResT = classify(E);
5570   auto prepareResult = [=]() -> bool {
5571     if (!ResT && !Initializing) {
5572       std::optional<unsigned> LocalIndex = allocateLocal(SubExpr);
5573       if (!LocalIndex)
5574         return false;
5575       return this->emitGetPtrLocal(*LocalIndex, E);
5576     }
5577 
5578     return true;
5579   };
5580 
5581   // The offset of the temporary, if we created one.
5582   unsigned SubExprOffset = ~0u;
5583   auto createTemp = [=, &SubExprOffset]() -> bool {
5584     SubExprOffset = this->allocateLocalPrimitive(SubExpr, PT_Ptr, true, false);
5585     if (!this->visit(SubExpr))
5586       return false;
5587     return this->emitSetLocal(PT_Ptr, SubExprOffset, E);
5588   };
5589 
5590   PrimType ElemT = classifyComplexElementType(SubExpr->getType());
5591   auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
5592     if (!this->emitGetLocal(PT_Ptr, Offset, E))
5593       return false;
5594     return this->emitArrayElemPop(ElemT, Index, E);
5595   };
5596 
5597   switch (E->getOpcode()) {
5598   case UO_Minus:
5599     if (!prepareResult())
5600       return false;
5601     if (!createTemp())
5602       return false;
5603     for (unsigned I = 0; I != 2; ++I) {
5604       if (!getElem(SubExprOffset, I))
5605         return false;
5606       if (!this->emitNeg(ElemT, E))
5607         return false;
5608       if (!this->emitInitElem(ElemT, I, E))
5609         return false;
5610     }
5611     break;
5612 
5613   case UO_Plus:   // +x
5614   case UO_AddrOf: // &x
5615   case UO_Deref:  // *x
5616     return this->delegate(SubExpr);
5617 
5618   case UO_LNot:
5619     if (!this->visit(SubExpr))
5620       return false;
5621     if (!this->emitComplexBoolCast(SubExpr))
5622       return false;
5623     if (!this->emitInv(E))
5624       return false;
5625     if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
5626       return this->emitCast(PT_Bool, ET, E);
5627     return true;
5628 
5629   case UO_Real:
5630     return this->emitComplexReal(SubExpr);
5631 
5632   case UO_Imag:
5633     if (!this->visit(SubExpr))
5634       return false;
5635 
5636     if (SubExpr->isLValue()) {
5637       if (!this->emitConstUint8(1, E))
5638         return false;
5639       return this->emitArrayElemPtrPopUint8(E);
5640     }
5641 
5642     // Since our _Complex implementation does not map to a primitive type,
5643     // we sometimes have to do the lvalue-to-rvalue conversion here manually.
5644     return this->emitArrayElemPop(classifyPrim(E->getType()), 1, E);
5645 
5646   case UO_Not: // ~x
5647     if (!this->visit(SubExpr))
5648       return false;
5649     // Negate the imaginary component.
5650     if (!this->emitArrayElem(ElemT, 1, E))
5651       return false;
5652     if (!this->emitNeg(ElemT, E))
5653       return false;
5654     if (!this->emitInitElem(ElemT, 1, E))
5655       return false;
5656     return DiscardResult ? this->emitPopPtr(E) : true;
5657 
5658   case UO_Extension:
5659     return this->delegate(SubExpr);
5660 
5661   default:
5662     return this->emitInvalid(E);
5663   }
5664 
5665   return true;
5666 }
5667 
5668 template <class Emitter>
5669 bool Compiler<Emitter>::VisitVectorUnaryOperator(const UnaryOperator *E) {
5670   const Expr *SubExpr = E->getSubExpr();
5671   assert(SubExpr->getType()->isVectorType());
5672 
5673   if (DiscardResult)
5674     return this->discard(SubExpr);
5675 
5676   auto UnaryOp = E->getOpcode();
5677   if (UnaryOp != UO_Plus && UnaryOp != UO_Minus && UnaryOp != UO_LNot &&
5678       UnaryOp != UO_Not && UnaryOp != UO_AddrOf)
5679     return this->emitInvalid(E);
5680 
5681   // Nothing to do here.
5682   if (UnaryOp == UO_Plus || UnaryOp == UO_AddrOf)
5683     return this->delegate(SubExpr);
5684 
5685   if (!Initializing) {
5686     std::optional<unsigned> LocalIndex = allocateLocal(SubExpr);
5687     if (!LocalIndex)
5688       return false;
5689     if (!this->emitGetPtrLocal(*LocalIndex, E))
5690       return false;
5691   }
5692 
5693   // The offset of the temporary, if we created one.
5694   unsigned SubExprOffset =
5695       this->allocateLocalPrimitive(SubExpr, PT_Ptr, true, false);
5696   if (!this->visit(SubExpr))
5697     return false;
5698   if (!this->emitSetLocal(PT_Ptr, SubExprOffset, E))
5699     return false;
5700 
5701   const auto *VecTy = SubExpr->getType()->getAs<VectorType>();
5702   PrimType ElemT = classifyVectorElementType(SubExpr->getType());
5703   auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
5704     if (!this->emitGetLocal(PT_Ptr, Offset, E))
5705       return false;
5706     return this->emitArrayElemPop(ElemT, Index, E);
5707   };
5708 
5709   switch (UnaryOp) {
5710   case UO_Minus:
5711     for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
5712       if (!getElem(SubExprOffset, I))
5713         return false;
5714       if (!this->emitNeg(ElemT, E))
5715         return false;
5716       if (!this->emitInitElem(ElemT, I, E))
5717         return false;
5718     }
5719     break;
5720   case UO_LNot: { // !x
5721     // In C++, the logic operators !, &&, || are available for vectors. !v is
5722     // equivalent to v == 0.
5723     //
5724     // The result of the comparison is a vector of the same width and number of
5725     // elements as the comparison operands with a signed integral element type.
5726     //
5727     // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html
5728     QualType ResultVecTy = E->getType();
5729     PrimType ResultVecElemT =
5730         classifyPrim(ResultVecTy->getAs<VectorType>()->getElementType());
5731     for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
5732       if (!getElem(SubExprOffset, I))
5733         return false;
5734       // operator ! on vectors returns -1 for 'truth', so negate it.
5735       if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
5736         return false;
5737       if (!this->emitInv(E))
5738         return false;
5739       if (!this->emitPrimCast(PT_Bool, ElemT, VecTy->getElementType(), E))
5740         return false;
5741       if (!this->emitNeg(ElemT, E))
5742         return false;
5743       if (ElemT != ResultVecElemT &&
5744           !this->emitPrimCast(ElemT, ResultVecElemT, ResultVecTy, E))
5745         return false;
5746       if (!this->emitInitElem(ResultVecElemT, I, E))
5747         return false;
5748     }
5749     break;
5750   }
5751   case UO_Not: // ~x
5752     for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
5753       if (!getElem(SubExprOffset, I))
5754         return false;
5755       if (ElemT == PT_Bool) {
5756         if (!this->emitInv(E))
5757           return false;
5758       } else {
5759         if (!this->emitComp(ElemT, E))
5760           return false;
5761       }
5762       if (!this->emitInitElem(ElemT, I, E))
5763         return false;
5764     }
5765     break;
5766   default:
5767     llvm_unreachable("Unsupported unary operators should be handled up front");
5768   }
5769   return true;
5770 }
5771 
5772 template <class Emitter>
5773 bool Compiler<Emitter>::visitDeclRef(const ValueDecl *D, const Expr *E) {
5774   if (DiscardResult)
5775     return true;
5776 
5777   if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
5778     return this->emitConst(ECD->getInitVal(), E);
5779   } else if (const auto *BD = dyn_cast<BindingDecl>(D)) {
5780     return this->visit(BD->getBinding());
5781   } else if (const auto *FuncDecl = dyn_cast<FunctionDecl>(D)) {
5782     const Function *F = getFunction(FuncDecl);
5783     return F && this->emitGetFnPtr(F, E);
5784   } else if (const auto *TPOD = dyn_cast<TemplateParamObjectDecl>(D)) {
5785     if (std::optional<unsigned> Index = P.getOrCreateGlobal(D)) {
5786       if (!this->emitGetPtrGlobal(*Index, E))
5787         return false;
5788       if (std::optional<PrimType> T = classify(E->getType())) {
5789         if (!this->visitAPValue(TPOD->getValue(), *T, E))
5790           return false;
5791         return this->emitInitGlobal(*T, *Index, E);
5792       }
5793       return this->visitAPValueInitializer(TPOD->getValue(), E);
5794     }
5795     return false;
5796   }
5797 
5798   // References are implemented via pointers, so when we see a DeclRefExpr
5799   // pointing to a reference, we need to get its value directly (i.e. the
5800   // pointer to the actual value) instead of a pointer to the pointer to the
5801   // value.
5802   bool IsReference = D->getType()->isReferenceType();
5803 
5804   // Check for local/global variables and parameters.
5805   if (auto It = Locals.find(D); It != Locals.end()) {
5806     const unsigned Offset = It->second.Offset;
5807     if (IsReference)
5808       return this->emitGetLocal(PT_Ptr, Offset, E);
5809     return this->emitGetPtrLocal(Offset, E);
5810   } else if (auto GlobalIndex = P.getGlobal(D)) {
5811     if (IsReference) {
5812       if (!Ctx.getLangOpts().CPlusPlus11)
5813         return this->emitGetGlobal(classifyPrim(E), *GlobalIndex, E);
5814       return this->emitGetGlobalUnchecked(classifyPrim(E), *GlobalIndex, E);
5815     }
5816 
5817     return this->emitGetPtrGlobal(*GlobalIndex, E);
5818   } else if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
5819     if (auto It = this->Params.find(PVD); It != this->Params.end()) {
5820       if (IsReference || !It->second.IsPtr)
5821         return this->emitGetParam(classifyPrim(E), It->second.Offset, E);
5822 
5823       return this->emitGetPtrParam(It->second.Offset, E);
5824     }
5825   }
5826 
5827   // In case we need to re-visit a declaration.
5828   auto revisit = [&](const VarDecl *VD) -> bool {
5829     auto VarState = this->visitDecl(VD);
5830 
5831     if (VarState.notCreated())
5832       return true;
5833     if (!VarState)
5834       return false;
5835     // Retry.
5836     return this->visitDeclRef(D, E);
5837   };
5838 
5839   // Handle lambda captures.
5840   if (auto It = this->LambdaCaptures.find(D);
5841       It != this->LambdaCaptures.end()) {
5842     auto [Offset, IsPtr] = It->second;
5843 
5844     if (IsPtr)
5845       return this->emitGetThisFieldPtr(Offset, E);
5846     return this->emitGetPtrThisField(Offset, E);
5847   } else if (const auto *DRE = dyn_cast<DeclRefExpr>(E);
5848              DRE && DRE->refersToEnclosingVariableOrCapture()) {
5849     if (const auto *VD = dyn_cast<VarDecl>(D); VD && VD->isInitCapture())
5850       return revisit(VD);
5851   }
5852 
5853   if (D != InitializingDecl) {
5854     // Try to lazily visit (or emit dummy pointers for) declarations
5855     // we haven't seen yet.
5856     if (Ctx.getLangOpts().CPlusPlus) {
5857       if (const auto *VD = dyn_cast<VarDecl>(D)) {
5858         const auto typeShouldBeVisited = [&](QualType T) -> bool {
5859           if (T.isConstant(Ctx.getASTContext()))
5860             return true;
5861           if (const auto *RT = T->getAs<ReferenceType>())
5862             return RT->getPointeeType().isConstQualified();
5863           return false;
5864         };
5865 
5866         // DecompositionDecls are just proxies for us.
5867         if (isa<DecompositionDecl>(VD))
5868           return revisit(VD);
5869 
5870         if ((VD->hasGlobalStorage() || VD->isStaticDataMember()) &&
5871             typeShouldBeVisited(VD->getType()))
5872           return revisit(VD);
5873 
5874         // FIXME: The evaluateValue() check here is a little ridiculous, since
5875         // it will ultimately call into Context::evaluateAsInitializer(). In
5876         // other words, we're evaluating the initializer, just to know if we can
5877         // evaluate the initializer.
5878         if (VD->isLocalVarDecl() && typeShouldBeVisited(VD->getType()) &&
5879             VD->getInit() && !VD->getInit()->isValueDependent() &&
5880             VD->evaluateValue())
5881           return revisit(VD);
5882       }
5883     } else {
5884       if (const auto *VD = dyn_cast<VarDecl>(D);
5885           VD && VD->getAnyInitializer() &&
5886           VD->getType().isConstant(Ctx.getASTContext()) && !VD->isWeak())
5887         return revisit(VD);
5888     }
5889   }
5890 
5891   if (std::optional<unsigned> I = P.getOrCreateDummy(D)) {
5892     if (!this->emitGetPtrGlobal(*I, E))
5893       return false;
5894     if (E->getType()->isVoidType())
5895       return true;
5896     // Convert the dummy pointer to another pointer type if we have to.
5897     if (PrimType PT = classifyPrim(E); PT != PT_Ptr) {
5898       if (isPtrType(PT))
5899         return this->emitDecayPtr(PT_Ptr, PT, E);
5900       return false;
5901     }
5902     return true;
5903   }
5904 
5905   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5906     return this->emitInvalidDeclRef(DRE, E);
5907   return false;
5908 }
5909 
5910 template <class Emitter>
5911 bool Compiler<Emitter>::VisitDeclRefExpr(const DeclRefExpr *E) {
5912   const auto *D = E->getDecl();
5913   return this->visitDeclRef(D, E);
5914 }
5915 
5916 template <class Emitter> void Compiler<Emitter>::emitCleanup() {
5917   for (VariableScope<Emitter> *C = VarScope; C; C = C->getParent())
5918     C->emitDestruction();
5919 }
5920 
5921 template <class Emitter>
5922 unsigned Compiler<Emitter>::collectBaseOffset(const QualType BaseType,
5923                                               const QualType DerivedType) {
5924   const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
5925     if (const auto *R = Ty->getPointeeCXXRecordDecl())
5926       return R;
5927     return Ty->getAsCXXRecordDecl();
5928   };
5929   const CXXRecordDecl *BaseDecl = extractRecordDecl(BaseType);
5930   const CXXRecordDecl *DerivedDecl = extractRecordDecl(DerivedType);
5931 
5932   return Ctx.collectBaseOffset(BaseDecl, DerivedDecl);
5933 }
5934 
5935 /// Emit casts from a PrimType to another PrimType.
5936 template <class Emitter>
5937 bool Compiler<Emitter>::emitPrimCast(PrimType FromT, PrimType ToT,
5938                                      QualType ToQT, const Expr *E) {
5939 
5940   if (FromT == PT_Float) {
5941     // Floating to floating.
5942     if (ToT == PT_Float) {
5943       const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
5944       return this->emitCastFP(ToSem, getRoundingMode(E), E);
5945     }
5946 
5947     if (ToT == PT_IntAP)
5948       return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(ToQT),
5949                                               getFPOptions(E), E);
5950     if (ToT == PT_IntAPS)
5951       return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(ToQT),
5952                                                getFPOptions(E), E);
5953 
5954     // Float to integral.
5955     if (isIntegralType(ToT) || ToT == PT_Bool)
5956       return this->emitCastFloatingIntegral(ToT, getFPOptions(E), E);
5957   }
5958 
5959   if (isIntegralType(FromT) || FromT == PT_Bool) {
5960     if (ToT == PT_IntAP)
5961       return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
5962     if (ToT == PT_IntAPS)
5963       return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
5964 
5965     // Integral to integral.
5966     if (isIntegralType(ToT) || ToT == PT_Bool)
5967       return FromT != ToT ? this->emitCast(FromT, ToT, E) : true;
5968 
5969     if (ToT == PT_Float) {
5970       // Integral to floating.
5971       const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
5972       return this->emitCastIntegralFloating(FromT, ToSem, getFPOptions(E), E);
5973     }
5974   }
5975 
5976   return false;
5977 }
5978 
5979 /// Emits __real(SubExpr)
5980 template <class Emitter>
5981 bool Compiler<Emitter>::emitComplexReal(const Expr *SubExpr) {
5982   assert(SubExpr->getType()->isAnyComplexType());
5983 
5984   if (DiscardResult)
5985     return this->discard(SubExpr);
5986 
5987   if (!this->visit(SubExpr))
5988     return false;
5989   if (SubExpr->isLValue()) {
5990     if (!this->emitConstUint8(0, SubExpr))
5991       return false;
5992     return this->emitArrayElemPtrPopUint8(SubExpr);
5993   }
5994 
5995   // Rvalue, load the actual element.
5996   return this->emitArrayElemPop(classifyComplexElementType(SubExpr->getType()),
5997                                 0, SubExpr);
5998 }
5999 
6000 template <class Emitter>
6001 bool Compiler<Emitter>::emitComplexBoolCast(const Expr *E) {
6002   assert(!DiscardResult);
6003   PrimType ElemT = classifyComplexElementType(E->getType());
6004   // We emit the expression (__real(E) != 0 || __imag(E) != 0)
6005   // for us, that means (bool)E[0] || (bool)E[1]
6006   if (!this->emitArrayElem(ElemT, 0, E))
6007     return false;
6008   if (ElemT == PT_Float) {
6009     if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
6010       return false;
6011   } else {
6012     if (!this->emitCast(ElemT, PT_Bool, E))
6013       return false;
6014   }
6015 
6016   // We now have the bool value of E[0] on the stack.
6017   LabelTy LabelTrue = this->getLabel();
6018   if (!this->jumpTrue(LabelTrue))
6019     return false;
6020 
6021   if (!this->emitArrayElemPop(ElemT, 1, E))
6022     return false;
6023   if (ElemT == PT_Float) {
6024     if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
6025       return false;
6026   } else {
6027     if (!this->emitCast(ElemT, PT_Bool, E))
6028       return false;
6029   }
6030   // Leave the boolean value of E[1] on the stack.
6031   LabelTy EndLabel = this->getLabel();
6032   this->jump(EndLabel);
6033 
6034   this->emitLabel(LabelTrue);
6035   if (!this->emitPopPtr(E))
6036     return false;
6037   if (!this->emitConstBool(true, E))
6038     return false;
6039 
6040   this->fallthrough(EndLabel);
6041   this->emitLabel(EndLabel);
6042 
6043   return true;
6044 }
6045 
6046 template <class Emitter>
6047 bool Compiler<Emitter>::emitComplexComparison(const Expr *LHS, const Expr *RHS,
6048                                               const BinaryOperator *E) {
6049   assert(E->isComparisonOp());
6050   assert(!Initializing);
6051   assert(!DiscardResult);
6052 
6053   PrimType ElemT;
6054   bool LHSIsComplex;
6055   unsigned LHSOffset;
6056   if (LHS->getType()->isAnyComplexType()) {
6057     LHSIsComplex = true;
6058     ElemT = classifyComplexElementType(LHS->getType());
6059     LHSOffset = allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true,
6060                                        /*IsExtended=*/false);
6061     if (!this->visit(LHS))
6062       return false;
6063     if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
6064       return false;
6065   } else {
6066     LHSIsComplex = false;
6067     PrimType LHST = classifyPrim(LHS->getType());
6068     LHSOffset = this->allocateLocalPrimitive(LHS, LHST, true, false);
6069     if (!this->visit(LHS))
6070       return false;
6071     if (!this->emitSetLocal(LHST, LHSOffset, E))
6072       return false;
6073   }
6074 
6075   bool RHSIsComplex;
6076   unsigned RHSOffset;
6077   if (RHS->getType()->isAnyComplexType()) {
6078     RHSIsComplex = true;
6079     ElemT = classifyComplexElementType(RHS->getType());
6080     RHSOffset = allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true,
6081                                        /*IsExtended=*/false);
6082     if (!this->visit(RHS))
6083       return false;
6084     if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
6085       return false;
6086   } else {
6087     RHSIsComplex = false;
6088     PrimType RHST = classifyPrim(RHS->getType());
6089     RHSOffset = this->allocateLocalPrimitive(RHS, RHST, true, false);
6090     if (!this->visit(RHS))
6091       return false;
6092     if (!this->emitSetLocal(RHST, RHSOffset, E))
6093       return false;
6094   }
6095 
6096   auto getElem = [&](unsigned LocalOffset, unsigned Index,
6097                      bool IsComplex) -> bool {
6098     if (IsComplex) {
6099       if (!this->emitGetLocal(PT_Ptr, LocalOffset, E))
6100         return false;
6101       return this->emitArrayElemPop(ElemT, Index, E);
6102     }
6103     return this->emitGetLocal(ElemT, LocalOffset, E);
6104   };
6105 
6106   for (unsigned I = 0; I != 2; ++I) {
6107     // Get both values.
6108     if (!getElem(LHSOffset, I, LHSIsComplex))
6109       return false;
6110     if (!getElem(RHSOffset, I, RHSIsComplex))
6111       return false;
6112     // And compare them.
6113     if (!this->emitEQ(ElemT, E))
6114       return false;
6115 
6116     if (!this->emitCastBoolUint8(E))
6117       return false;
6118   }
6119 
6120   // We now have two bool values on the stack. Compare those.
6121   if (!this->emitAddUint8(E))
6122     return false;
6123   if (!this->emitConstUint8(2, E))
6124     return false;
6125 
6126   if (E->getOpcode() == BO_EQ) {
6127     if (!this->emitEQUint8(E))
6128       return false;
6129   } else if (E->getOpcode() == BO_NE) {
6130     if (!this->emitNEUint8(E))
6131       return false;
6132   } else
6133     return false;
6134 
6135   // In C, this returns an int.
6136   if (PrimType ResT = classifyPrim(E->getType()); ResT != PT_Bool)
6137     return this->emitCast(PT_Bool, ResT, E);
6138   return true;
6139 }
6140 
6141 /// When calling this, we have a pointer of the local-to-destroy
6142 /// on the stack.
6143 /// Emit destruction of record types (or arrays of record types).
6144 template <class Emitter>
6145 bool Compiler<Emitter>::emitRecordDestruction(const Record *R) {
6146   assert(R);
6147   const CXXDestructorDecl *Dtor = R->getDestructor();
6148   if (!Dtor || Dtor->isTrivial())
6149     return true;
6150 
6151   assert(Dtor);
6152   const Function *DtorFunc = getFunction(Dtor);
6153   if (!DtorFunc)
6154     return false;
6155   assert(DtorFunc->hasThisPointer());
6156   assert(DtorFunc->getNumParams() == 1);
6157   if (!this->emitDupPtr(SourceInfo{}))
6158     return false;
6159   return this->emitCall(DtorFunc, 0, SourceInfo{});
6160 }
6161 /// When calling this, we have a pointer of the local-to-destroy
6162 /// on the stack.
6163 /// Emit destruction of record types (or arrays of record types).
6164 template <class Emitter>
6165 bool Compiler<Emitter>::emitDestruction(const Descriptor *Desc) {
6166   assert(Desc);
6167   assert(!Desc->isPrimitive());
6168   assert(!Desc->isPrimitiveArray());
6169 
6170   // Arrays.
6171   if (Desc->isArray()) {
6172     const Descriptor *ElemDesc = Desc->ElemDesc;
6173     assert(ElemDesc);
6174 
6175     // Don't need to do anything for these.
6176     if (ElemDesc->isPrimitiveArray())
6177       return true;
6178 
6179     // If this is an array of record types, check if we need
6180     // to call the element destructors at all. If not, try
6181     // to save the work.
6182     if (const Record *ElemRecord = ElemDesc->ElemRecord) {
6183       if (const CXXDestructorDecl *Dtor = ElemRecord->getDestructor();
6184           !Dtor || Dtor->isTrivial())
6185         return true;
6186     }
6187 
6188     for (ssize_t I = Desc->getNumElems() - 1; I >= 0; --I) {
6189       if (!this->emitConstUint64(I, SourceInfo{}))
6190         return false;
6191       if (!this->emitArrayElemPtrUint64(SourceInfo{}))
6192         return false;
6193       if (!this->emitDestruction(ElemDesc))
6194         return false;
6195       if (!this->emitPopPtr(SourceInfo{}))
6196         return false;
6197     }
6198     return true;
6199   }
6200 
6201   assert(Desc->ElemRecord);
6202   return this->emitRecordDestruction(Desc->ElemRecord);
6203 }
6204 
6205 namespace clang {
6206 namespace interp {
6207 
6208 template class Compiler<ByteCodeEmitter>;
6209 template class Compiler<EvalEmitter>;
6210 
6211 } // namespace interp
6212 } // namespace clang
6213