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