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