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