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