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