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